doover-core 0.1.2

Core library for doover: session-scoped snapshot, journal, and undo for AI agent shell actions
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
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! T4 — journal test suite (doover-implementation-plan.md §3).
//! Written before the journal module exists; drives its design.
//!
//! Design constraints from the live hook capture (fixtures README):
//! - there is no exit code; success == a PostToolUse arrived
//! - failed commands emit NO post event → pendings are closed as `abandoned`
//!   when the next action starts or the session ends
//! - `tool_use_id` correlates pre/post pairs

use doover_core::journal::{ActionKind, ActionStatus, Journal, ManifestRole, NewAction};
use doover_core::snapshot::{Store, StoreOptions};
use std::io::BufRead;
use std::path::Path;

fn mem_paths() -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("journal.db");
    (tmp, db)
}

fn new_action<'a>(session: &'a str, cmd: &'a str, tool_use: Option<&'a str>) -> NewAction<'a> {
    NewAction {
        session_id: session,
        tool_use_id: tool_use,
        raw_command: cmd,
        effect: "destructive",
        rule_id: Some("coreutils.rm"),
        has_unknown: false,
    }
}

/// Snapshot a real file so manifests carry a genuine store hash.
fn manifest_with_content(dir: &Path, name: &str, content: &str) -> doover_core::snapshot::Manifest {
    let store = Store::open_with(dir.join("store"), StoreOptions::default()).unwrap();
    let f = dir.join(name);
    std::fs::write(&f, content).unwrap();
    store.snapshot(&f, None).unwrap()
}

// --- schema & lifecycle --------------------------------------------------------

#[test]
fn open_creates_wal_schema_and_reopen_preserves() {
    let (_tmp, db) = mem_paths();
    {
        let j = Journal::open(&db).unwrap();
        j.begin_session("s1", "claude-code", "/tmp/proj").unwrap();
        j.start_action(&new_action("s1", "rm -rf ./x", Some("toolu_1")))
            .unwrap();
    }
    // the name says WAL: assert it (audit round 3 — a claim without an assertion)
    let conn = rusqlite::Connection::open(&db).unwrap();
    let mode: String = conn
        .query_row("PRAGMA journal_mode", [], |r| r.get(0))
        .unwrap();
    assert_eq!(mode.to_lowercase(), "wal");

    let j = Journal::open(&db).unwrap(); // reopen
    let actions = j.session_actions("s1").unwrap();
    assert_eq!(actions.len(), 1);
    assert_eq!(actions[0].raw_command, "rm -rf ./x");
    assert_eq!(actions[0].seq, 1);
}

#[test]
fn resumed_session_updates_cwd() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/old/place").unwrap();
    j.begin_session("s1", "claude-code", "/new/place").unwrap();
    let cwd: String = rusqlite::Connection::open(&db)
        .unwrap()
        .query_row("SELECT cwd FROM sessions WHERE id = 's1'", [], |r| r.get(0))
        .unwrap();
    assert_eq!(
        cwd, "/new/place",
        "a resumed session's cwd must not go stale"
    );
}

#[test]
fn a_future_schema_journal_refuses_to_open() {
    // journals outlive binaries: a DB written by a newer doover must refuse,
    // not silently operate on a schema it doesn't understand (audit round 6)
    let (_tmp, db) = mem_paths();
    drop(Journal::open(&db).unwrap());
    rusqlite::Connection::open(&db)
        .unwrap()
        .pragma_update(None, "user_version", 999)
        .unwrap();
    match Journal::open(&db) {
        Ok(_) => panic!("a future-schema journal must refuse to open"),
        Err(e) => assert!(e.to_string().contains("newer"), "got: {e}"),
    }
}

#[test]
fn a_v1_journal_migrates_to_v2_preserving_manifests_as_pre() {
    // step 6 added manifest roles; v1 rows must surface as role='pre'
    let (tmp, db) = mem_paths();
    // build a genuine v1 database by hand
    {
        let conn = rusqlite::Connection::open(&db).unwrap();
        conn.execute_batch(
            "CREATE TABLE sessions(id TEXT PRIMARY KEY, harness TEXT NOT NULL,
                cwd TEXT NOT NULL, started_at_ms INTEGER NOT NULL, ended_at_ms INTEGER);
             CREATE TABLE actions(id INTEGER PRIMARY KEY, session_id TEXT NOT NULL,
                seq INTEGER NOT NULL, kind TEXT NOT NULL, tool_use_id TEXT,
                raw_command TEXT NOT NULL, effect TEXT NOT NULL, rule_id TEXT,
                has_unknown INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL,
                target_action_id INTEGER, target_prior_status TEXT,
                pinned INTEGER NOT NULL DEFAULT 0, started_at_ms INTEGER NOT NULL,
                duration_ms INTEGER, note TEXT, UNIQUE(session_id, seq));
             CREATE TABLE manifests(id INTEGER PRIMARY KEY, action_id INTEGER NOT NULL,
                path TEXT NOT NULL, manifest_json TEXT NOT NULL, hashes TEXT NOT NULL,
                truncated INTEGER NOT NULL);
             PRAGMA user_version = 1;",
        )
        .unwrap();
        // one v1 action with one v1 manifest
        conn.execute(
            "INSERT INTO sessions(id, harness, cwd, started_at_ms) VALUES ('s1','claude-code','/p',1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO actions(session_id, seq, kind, raw_command, effect, status, started_at_ms)
             VALUES ('s1', 1, 'command', 'rm x', 'destructive', 'completed', 1)",
            [],
        )
        .unwrap();
        let m = manifest_with_content(tmp.path(), "legacy.txt", "v1 era bytes");
        conn.execute(
            "INSERT INTO manifests(action_id, path, manifest_json, hashes, truncated)
             VALUES (1, ?1, ?2, '[]', 0)",
            rusqlite::params![m.path.to_string_lossy(), serde_json::to_string(&m).unwrap()],
        )
        .unwrap();
    }

    let j = Journal::open(&db).unwrap(); // migrates 1 -> 2
    let pre = j.manifests_by_role(1, ManifestRole::Pre).unwrap();
    assert_eq!(pre.len(), 1, "legacy manifests default to role=pre");
    assert!(
        j.manifests_by_role(1, ManifestRole::Post)
            .unwrap()
            .is_empty()
    );
    let v: i64 = rusqlite::Connection::open(&db)
        .unwrap()
        .query_row("PRAGMA user_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(v, 2);
}

#[test]
fn garbage_file_is_a_clear_error_not_a_panic() {
    let (_tmp, db) = mem_paths();
    std::fs::write(&db, "this is not a sqlite database, honest").unwrap();
    assert!(Journal::open(&db).is_err());
}

#[test]
fn sequences_are_per_session_and_monotonic() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/a").unwrap();
    j.begin_session("s2", "claude-code", "/b").unwrap();
    let a1 = j.start_action(&new_action("s1", "ls", None)).unwrap();
    let a2 = j.start_action(&new_action("s1", "pwd", None)).unwrap();
    let b1 = j.start_action(&new_action("s2", "ls", None)).unwrap();
    assert_eq!(j.action(a1).unwrap().seq, 1);
    assert_eq!(j.action(a2).unwrap().seq, 2);
    assert_eq!(
        j.action(b1).unwrap().seq,
        1,
        "sessions sequence independently"
    );
}

#[test]
fn concurrent_writers_get_unique_contiguous_seqs() {
    // hook invocations are separate processes: model with two connections
    // racing on one session
    let (_tmp, db) = mem_paths();
    Journal::open(&db)
        .unwrap()
        .begin_session("s1", "claude-code", "/p")
        .unwrap();
    const N: usize = 40;
    let db2 = db.clone();
    let t = std::thread::spawn(move || {
        let j = Journal::open(&db2).unwrap();
        for i in 0..N {
            j.start_action(&new_action("s1", &format!("t2-{i}"), None))
                .unwrap();
        }
    });
    let j = Journal::open(&db).unwrap();
    for i in 0..N {
        j.start_action(&new_action("s1", &format!("t1-{i}"), None))
            .unwrap();
    }
    t.join().unwrap();
    let mut seqs: Vec<i64> = j
        .session_actions("s1")
        .unwrap()
        .iter()
        .map(|a| a.seq)
        .collect();
    seqs.sort_unstable();
    assert_eq!(
        seqs,
        (1..=(2 * N as i64)).collect::<Vec<_>>(),
        "unique and contiguous"
    );
}

// --- the missing-post rule -------------------------------------------------------

#[test]
fn pending_without_post_is_abandoned_when_next_action_starts() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "false", Some("toolu_a")))
        .unwrap();
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Pending);

    let b = j
        .start_action(&new_action("s1", "ls", Some("toolu_b")))
        .unwrap();
    assert_eq!(
        j.action(a).unwrap().status,
        ActionStatus::Abandoned,
        "no post event ever came for `false` — closed at next action"
    );
    assert_eq!(j.action(b).unwrap().status, ActionStatus::Pending);
}

#[test]
fn end_session_abandons_remaining_pendings_and_stamps_end() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j.start_action(&new_action("s1", "false", None)).unwrap();
    j.end_session("s1").unwrap();
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Abandoned);
}

#[test]
fn completion_correlates_by_tool_use_id() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("toolu_abc")))
        .unwrap();
    let completed = j.complete_by_tool_use("s1", "toolu_abc", 994).unwrap();
    assert_eq!(completed, a);
    let rec = j.action(a).unwrap();
    assert_eq!(rec.status, ActionStatus::Completed);
    assert_eq!(rec.duration_ms, Some(994));

    // unknown correlation id is a loud error, not a silent no-op
    assert!(j.complete_by_tool_use("s1", "toolu_nope", 1).is_err());
}

#[test]
fn late_post_after_abandonment_self_heals_to_completed() {
    // interleaved/background tool calls could deliver a post AFTER the next
    // action's start already abandoned its pre; a late post is better data
    // than our guess and must win
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "slow-thing", Some("toolu_slow")))
        .unwrap();
    let _b = j
        .start_action(&new_action("s1", "next", Some("toolu_next")))
        .unwrap();
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Abandoned);

    let healed = j.complete_by_tool_use("s1", "toolu_slow", 1234).unwrap();
    assert_eq!(healed, a);
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Completed);
    assert_eq!(j.action(a).unwrap().duration_ms, Some(1234));
}

// --- manifests -------------------------------------------------------------------

#[test]
fn manifest_round_trips_exactly() {
    let (tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm фото.jpg", Some("t1")))
        .unwrap();
    let m = manifest_with_content(tmp.path(), "фото 📸.jpg", "precious bytes");
    j.attach_manifest(a, &m, ManifestRole::Pre).unwrap();

    let stored = j.manifests(a).unwrap();
    assert_eq!(stored.len(), 1);
    assert_eq!(stored[0], m, "serde round-trip must be lossless");
}

#[test]
fn manifest_from_a_newer_doover_is_refused_loudly() {
    // journals outlive binaries: a manifest written by a future schema must
    // refuse, not misparse
    let (tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("t1")))
        .unwrap();
    let m = manifest_with_content(tmp.path(), "f.txt", "bytes");
    j.attach_manifest(a, &m, ManifestRole::Pre).unwrap();

    // simulate a future doover having written this manifest
    let conn = rusqlite::Connection::open(&db).unwrap();
    conn.execute(
        "UPDATE manifests SET manifest_json =
            json_set(manifest_json, '$.schema', 999)",
        [],
    )
    .unwrap();

    let err = j.manifests(a).unwrap_err();
    assert!(
        err.to_string().contains("newer"),
        "must explain the version problem, got: {err}"
    );
}

#[test]
fn legacy_manifest_json_without_schema_field_still_reads() {
    // pre-versioning JSON deserializes with schema=0 rather than erroring
    let (tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("t1")))
        .unwrap();
    let m = manifest_with_content(tmp.path(), "f.txt", "bytes");
    j.attach_manifest(a, &m, ManifestRole::Pre).unwrap();

    let conn = rusqlite::Connection::open(&db).unwrap();
    conn.execute(
        "UPDATE manifests SET manifest_json = json_remove(manifest_json, '$.schema')",
        [],
    )
    .unwrap();

    let stored = j.manifests(a).unwrap();
    assert_eq!(stored[0].schema, 0, "missing field defaults to 0 (legacy)");
    assert_eq!(stored[0].entries, m.entries, "content unaffected");
}

// --- undo chains -----------------------------------------------------------------

#[test]
fn undo_is_an_action_and_undo_of_undo_is_redo() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("t1")))
        .unwrap();
    j.complete_by_tool_use("s1", "t1", 5).unwrap();

    // undo: a new journaled action, target marked undone
    let u = j.record_undo("s1", a).unwrap();
    let u_rec = j.action(u).unwrap();
    assert_eq!(u_rec.kind, ActionKind::Undo);
    assert_eq!(u_rec.target_action_id, Some(a));
    assert_eq!(u_rec.status, ActionStatus::Completed);
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Undone);
    assert!(
        u_rec.seq > j.action(a).unwrap().seq,
        "history is append-only"
    );

    // redo: undoing the undo flips the original back
    let r = j.record_undo("s1", u).unwrap();
    assert_eq!(j.action(u).unwrap().status, ActionStatus::Undone);
    assert_eq!(
        j.action(a).unwrap().status,
        ActionStatus::Completed,
        "undo-of-undo restores the original's status"
    );
    assert_eq!(j.action(r).unwrap().kind, ActionKind::Undo);
}

#[test]
fn double_undo_is_refused() {
    // audit round 3: undoing an already-undone target appended duplicate rows
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("t1")))
        .unwrap();
    j.complete_by_tool_use("s1", "t1", 1).unwrap();
    j.record_undo("s1", a).unwrap();
    assert!(
        j.record_undo("s1", a).is_err(),
        "undoing an undone action must be refused (redo targets the undo, not the original)"
    );
}

#[test]
fn concurrent_double_undo_admits_exactly_one() {
    // audit round 3: the status check lived outside the transaction (TOCTOU)
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("t1")))
        .unwrap();
    j.complete_by_tool_use("s1", "t1", 1).unwrap();

    let db2 = db.clone();
    let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
    let b2 = barrier.clone();
    let h = std::thread::spawn(move || {
        let j2 = Journal::open(&db2).unwrap();
        b2.wait();
        j2.record_undo("s1", a).is_ok()
    });
    barrier.wait();
    let r1 = j.record_undo("s1", a).is_ok();
    let r2 = h.join().unwrap();
    assert!(r1 ^ r2, "exactly one racer may win, got r1={r1} r2={r2}");
    let undo_rows = j
        .session_actions("s1")
        .unwrap()
        .iter()
        .filter(|r| r.target_action_id == Some(a))
        .count();
    assert_eq!(undo_rows, 1, "one target, one undo row");
}

#[test]
fn redo_restores_prior_status_not_a_fabricated_completed() {
    // audit round 3: redo hardcoded 'completed' even for abandoned targets
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "false", Some("t1")))
        .unwrap();
    j.end_session("s1").unwrap(); // a -> abandoned (no post ever came)

    let u = j.record_undo("s1", a).unwrap();
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Undone);
    assert_eq!(
        j.action(u).unwrap().target_prior_status,
        Some(ActionStatus::Abandoned),
        "the undo row must remember what it undid"
    );

    j.record_undo("s1", u).unwrap(); // redo
    assert_eq!(
        j.action(a).unwrap().status,
        ActionStatus::Abandoned,
        "redo must restore the TRUE prior status, never invent 'completed'"
    );
}

#[test]
fn duplicate_tool_use_id_completes_only_the_newest() {
    // audit round 3: an unbounded UPDATE completed every matching row
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "cmd-one", Some("dup")))
        .unwrap();
    let b = j
        .start_action(&new_action("s1", "cmd-two", Some("dup")))
        .unwrap();

    let completed = j.complete_by_tool_use("s1", "dup", 7).unwrap();
    assert_eq!(completed, b, "the newest matching action wins");
    assert_eq!(j.action(b).unwrap().status, ActionStatus::Completed);
    assert_eq!(
        j.action(a).unwrap().status,
        ActionStatus::Abandoned,
        "the older duplicate keeps its abandoned status"
    );
}

#[test]
fn undoing_a_pending_action_is_refused() {
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j.start_action(&new_action("s1", "rm x", None)).unwrap();
    assert!(
        j.record_undo("s1", a).is_err(),
        "cannot undo an in-flight action"
    );
}

#[test]
fn undo_of_a_redo_is_refused_with_pointer_to_the_original() {
    // audit round 4: cascading status through undo-of-redo chains is where
    // round 3's fix broke down; the design answer is to bound the chain —
    // command actions and first-level undos (redo) are undoable, deeper is
    // refused with guidance
    let (_tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();
    let a = j
        .start_action(&new_action("s1", "rm x", Some("t1")))
        .unwrap();
    j.complete_by_tool_use("s1", "t1", 1).unwrap();
    let u1 = j.record_undo("s1", a).unwrap();
    let r1 = j.record_undo("s1", u1).unwrap(); // redo — allowed

    let err = j.record_undo("s1", r1).unwrap_err();
    assert!(
        err.to_string().contains(&format!("original action {a}")),
        "refusal must point at the original, got: {err}"
    );
    // refusal must not perturb any status
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Completed);
    assert_eq!(j.action(u1).unwrap().status, ActionStatus::Undone);
    assert_eq!(j.action(r1).unwrap().status, ActionStatus::Completed);

    // the sanctioned path still works: undo the original again
    let u2 = j.record_undo("s1", a).unwrap();
    assert_eq!(j.action(a).unwrap().status, ActionStatus::Undone);
    assert_eq!(j.action(u2).unwrap().status, ActionStatus::Completed);
}

// --- exhaustive small-model check (audit round 4) ---------------------------------
//
// Four audit rounds in a row found bugs one step past the hand-picked test
// paths. For a state machine the structural fix is exhaustive small-model
// testing: a trivially-correct reference model in the test, every sequence of
// undo attempts to depth 4, journal behavior compared against the model after
// every step.

mod small_model {
    use super::*;

    #[derive(Clone, Copy, PartialEq, Debug)]
    enum MStatus {
        Pending,
        Completed,
        Abandoned,
        Undone,
    }

    #[derive(Clone)]
    struct MAction {
        is_undo: bool,
        status: MStatus,
        target: Option<usize>,
        prior: Option<MStatus>,
    }

    /// Reference semantics: succeed iff target is completed/abandoned AND is a
    /// command or a first-level undo; on success append the undo, flip the
    /// target, and (for redo) restore the original's recorded prior status.
    fn model_apply(model: &mut Vec<MAction>, t: usize) -> bool {
        let tr = model[t].clone();
        if !matches!(tr.status, MStatus::Completed | MStatus::Abandoned) {
            return false;
        }
        if tr.is_undo && model[tr.target.unwrap()].is_undo {
            return false; // undo of a redo: bounded chain
        }
        model.push(MAction {
            is_undo: true,
            status: MStatus::Completed,
            target: Some(t),
            prior: Some(tr.status),
        });
        model[t].status = MStatus::Undone;
        if tr.is_undo {
            let original = tr.target.unwrap();
            model[original].status = tr.prior.unwrap();
        }
        true
    }

    fn to_model_status(s: ActionStatus) -> MStatus {
        match s {
            ActionStatus::Pending => MStatus::Pending,
            ActionStatus::Completed => MStatus::Completed,
            ActionStatus::Abandoned => MStatus::Abandoned,
            ActionStatus::Undone => MStatus::Undone,
        }
    }

    /// One journal per sequence: a completed, b abandoned, c pending.
    fn fresh() -> (tempfile::TempDir, Journal, Vec<i64>, Vec<MAction>) {
        let tmp = tempfile::tempdir().unwrap();
        let j = Journal::open(&tmp.path().join("j.db")).unwrap();
        j.begin_session("s1", "claude-code", "/p").unwrap();
        let a = j.start_action(&new_action("s1", "a", Some("ta"))).unwrap();
        j.complete_by_tool_use("s1", "ta", 1).unwrap();
        let b = j.start_action(&new_action("s1", "b", Some("tb"))).unwrap();
        let c = j.start_action(&new_action("s1", "c", Some("tc"))).unwrap(); // abandons b
        let ids = vec![a, b, c];
        let model = vec![
            MAction {
                is_undo: false,
                status: MStatus::Completed,
                target: None,
                prior: None,
            },
            MAction {
                is_undo: false,
                status: MStatus::Abandoned,
                target: None,
                prior: None,
            },
            MAction {
                is_undo: false,
                status: MStatus::Pending,
                target: None,
                prior: None,
            },
        ];
        (tmp, j, ids, model)
    }

    fn run_sequence(seq: &[usize]) -> Result<(), String> {
        let (_tmp, j, mut ids, mut model) = fresh();
        for (step, &t) in seq.iter().enumerate() {
            if t >= model.len() {
                return Ok(()); // target doesn't exist yet in this sequence; skip
            }
            let expect_ok = model_apply(&mut model, t);
            let got = j.record_undo("s1", ids[t]);
            if expect_ok != got.is_ok() {
                return Err(format!(
                    "seq {seq:?} step {step}: model says ok={expect_ok}, journal says {got:?}"
                ));
            }
            if let Ok(id) = got {
                ids.push(id);
            }
            // compare the FULL record, not just status (audit round 5: a bug
            // that corrupts target_prior_status or kind while leaving status
            // correct would otherwise pass silently)
            for (i, m) in model.iter().enumerate() {
                let rec = j.action(ids[i]).unwrap();
                if to_model_status(rec.status) != m.status {
                    return Err(format!(
                        "seq {seq:?} step {step}: action #{i} status model={:?} journal={:?}",
                        m.status, rec.status
                    ));
                }
                let want_kind_undo = m.is_undo;
                let got_kind_undo = rec.kind == ActionKind::Undo;
                if want_kind_undo != got_kind_undo {
                    return Err(format!(
                        "seq {seq:?} step {step}: action #{i} kind mismatch (model undo={want_kind_undo})"
                    ));
                }
                let got_prior = rec.target_prior_status.map(to_model_status);
                if got_prior != m.prior {
                    return Err(format!(
                        "seq {seq:?} step {step}: action #{i} target_prior_status model={:?} journal={:?}",
                        m.prior, got_prior
                    ));
                }
            }
        }
        Ok(())
    }

    #[test]
    fn every_undo_sequence_to_depth_4_matches_the_reference_model() {
        // targets can reference actions created mid-sequence: enumerate over a
        // generous index space and skip not-yet-existing targets
        const DEPTH: usize = 4;
        const MAX_IDX: usize = 7; // 3 initial + up to 4 created
        let mut failures = Vec::new();
        let mut checked = 0usize;

        let mut seq = vec![0usize; DEPTH];
        'outer: loop {
            if let Err(msg) = run_sequence(&seq) {
                failures.push(msg);
                if failures.len() > 5 {
                    break;
                }
            }
            checked += 1;
            // odometer increment
            for d in (0..DEPTH).rev() {
                seq[d] += 1;
                if seq[d] < MAX_IDX {
                    continue 'outer;
                }
                seq[d] = 0;
            }
            break;
        }
        // `checked` counts enumerated tuples; many truncate at step 1 when
        // their target does not yet exist, so the number of DISTINCT valid
        // undo paths exercised is smaller — the guard just pins the
        // enumeration breadth, it is not a "sequences tested" headline.
        assert!(
            failures.is_empty(),
            "journal diverges from the reference model:\n{}",
            failures.join("\n")
        );
        assert!(checked >= 2000, "enumeration breadth shrank: {checked}");
    }
}

// --- GC support ------------------------------------------------------------------

#[test]
fn live_hashes_honor_pins_and_recency() {
    let (tmp, db) = mem_paths();
    let j = Journal::open(&db).unwrap();
    j.begin_session("s1", "claude-code", "/p").unwrap();

    let mk = |name: &str, content: &str| manifest_with_content(tmp.path(), name, content);
    let h = |m: &doover_core::snapshot::Manifest| -> String {
        match &m.entries[0].kind {
            doover_core::snapshot::EntryKind::File { hash, .. } => hash.clone(),
            other => panic!("expected file entry, got {other:?}"),
        }
    };

    let old_unpinned = j.start_action(&new_action("s1", "a", Some("t1"))).unwrap();
    let m1 = mk("f1", "content one");
    j.attach_manifest(old_unpinned, &m1, ManifestRole::Pre)
        .unwrap();

    let old_pinned = j.start_action(&new_action("s1", "b", Some("t2"))).unwrap();
    let m2 = mk("f2", "content two");
    j.attach_manifest(old_pinned, &m2, ManifestRole::Pre)
        .unwrap();
    j.set_pinned(old_pinned, true).unwrap();

    let cutoff = doover_core::journal::now_ms() + 1;
    std::thread::sleep(std::time::Duration::from_millis(5));

    let recent = j.start_action(&new_action("s1", "c", Some("t3"))).unwrap();
    let m3 = mk("f3", "content three");
    j.attach_manifest(recent, &m3, ManifestRole::Pre).unwrap();

    let live = j.live_hashes(cutoff).unwrap();
    assert!(!live.contains(&h(&m1)), "old + unpinned is collectable");
    assert!(live.contains(&h(&m2)), "pinned survives regardless of age");
    assert!(live.contains(&h(&m3)), "recent survives regardless of pin");
}

// --- crash safety ----------------------------------------------------------------

/// Child half of the kill-9 test: writes one committed action, then leaves a
/// second insert dangling inside an open transaction and blocks forever.
/// Skipped unless invoked by the parent below.
#[test]
fn kill9_child_writer() {
    let Ok(db) = std::env::var("DOOVER_T4_CHILD_DB") else {
        return;
    };
    let j = Journal::open(Path::new(&db)).unwrap();
    j.begin_session("crash", "claude-code", "/p").unwrap();
    j.start_action(&new_action("crash", "committed-before-crash", Some("t1")))
        .unwrap();

    // raw uncommitted write through a second connection
    let conn = rusqlite::Connection::open(&db).unwrap();
    conn.busy_timeout(std::time::Duration::from_secs(5))
        .unwrap();
    conn.execute_batch("BEGIN IMMEDIATE;").unwrap();
    conn.execute(
        "INSERT INTO actions(session_id, seq, kind, raw_command, effect, status, started_at_ms)
         VALUES ('crash', 999, 'command', 'torn-write-should-vanish', 'safe', 'pending', 0)",
        [],
    )
    .unwrap();
    println!("READY");
    std::thread::sleep(std::time::Duration::from_secs(60)); // parent kill -9s us here
}

#[test]
fn kill9_mid_transaction_leaves_no_torn_rows() {
    let (_tmp, db) = mem_paths();
    let exe = std::env::current_exe().unwrap();
    let mut child = std::process::Command::new(exe)
        .args(["kill9_child_writer", "--exact", "--nocapture"])
        .env("DOOVER_T4_CHILD_DB", &db)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    let stdout = child.stdout.take().unwrap();
    let mut lines = std::io::BufReader::new(stdout).lines();
    loop {
        let line = lines.next().expect("child exited before READY").unwrap();
        if line.trim() == "READY" {
            break;
        }
    }
    // SIGKILL: no destructors, no rollback — WAL must recover on next open
    child.kill().unwrap();
    child.wait().unwrap();

    let j = Journal::open(&db).unwrap();
    let actions = j.session_actions("crash").unwrap();
    assert_eq!(
        actions.len(),
        1,
        "uncommitted row must not survive: {actions:?}"
    );
    assert_eq!(actions[0].raw_command, "committed-before-crash");
    assert!(
        j.integrity_check().unwrap(),
        "database must pass integrity_check"
    );

    // and the journal is fully writable afterwards
    let after = j
        .start_action(&new_action("crash", "post-crash-write", None))
        .unwrap();
    assert_eq!(j.action(after).unwrap().seq, 2);
}

/// Round 20 (found by the S9 concurrency stress e2e): concurrent FIRST opens
/// of a fresh journal raced the schema migration — every loser died on
/// `duplicate column name: role`, every hook failed open, and nothing was
/// protected on a brand-new install with parallel agents. All simultaneous
/// opens must succeed.
#[test]
fn concurrent_first_opens_do_not_race_the_migration() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("journal.db");
    let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
    let handles: Vec<_> = (0..8)
        .map(|_| {
            let db = db.clone();
            let barrier = barrier.clone();
            std::thread::spawn(move || {
                barrier.wait(); // maximal simultaneity
                Journal::open(&db).map(|_| ())
            })
        })
        .collect();
    for (i, h) in handles.into_iter().enumerate() {
        h.join()
            .unwrap()
            .unwrap_or_else(|e| panic!("concurrent open #{i} failed the migration race: {e}"));
    }
}

/// D4: the journal stores raw commands (which may embed secrets) in
/// plaintext — the DB file must be owner-only, umask notwithstanding.
#[test]
fn journal_file_is_owner_only() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("journal.db");
    let _j = Journal::open(&db).unwrap();
    let mode = std::fs::metadata(&db).unwrap().permissions().mode() & 0o777;
    assert_eq!(mode, 0o600, "journal must be 0600, got {mode:o}");
}