velra 0.1.1

Lossless compaction for Claude Code: task continuity across context compactions.
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
//! Shared harness for the acceptance suite (§21).
#![allow(dead_code)]

use assert_cmd::Command;
use serde_json::{json, Value};
use std::path::PathBuf;
use std::time::{Duration, Instant};
use velra_core::checkpoint::{self, CheckpointRequest};
use velra_core::db::{Db, Role};
use velra_core::event::{dedupe_key, NewEvent, Payload, ProjectInfo};
use velra_core::model::Trigger;
use velra_core::render::{RenderConfig, Snapshot};
use velra_core::snapshot::SnapshotMeta;
use velra_core::{eventlog, hash, paths, reducer};

/// The watchdog every test subprocess runs with. The production deadline is
/// 250 ms (§4); a loaded CI runner can spend that long on process start and
/// first-run schema creation alone, and a deadline that fires mid-write
/// diverts the event to the spool (§10.3) — correct behaviour that is
/// nonetheless invisible to a test that queries the table directly. Tests
/// that measure the deadline itself use `cmd_with_real_watchdog`.
///
/// The binary honours the knob only under the `fault-injection` feature,
/// which is how CI builds (`--all-features`); a default `cargo test` build
/// ignores it and relies on the drain helpers below instead.
pub const TEST_WATCHDOG_MS: &str = "60000";

/// How long a drained query waits for a row to become visible. Long enough
/// to absorb NTFS write buffering and a SQLite lock handoff on a contended
/// runner, short enough that a genuine failure still fails quickly.
pub const DRAIN_TIMEOUT: Duration = Duration::from_secs(3);

/// Gap between drain attempts.
const DRAIN_POLL: Duration = Duration::from_millis(50);

/// How long a test connection waits for a lock rather than returning
/// `DbError::Busy`, which on a contended runner is a flake, not a result.
const TEST_BUSY_TIMEOUT: Duration = Duration::from_secs(5);

/// 2026-09-12T10:04:05Z — every test clock starts here so output is stable.
pub const BASE_MS: i64 = 1_789_207_445_000;

/// An isolated `$VELRA_HOME` + settings dir + project dir.
pub struct Env {
    pub dir: tempfile::TempDir,
    pub home: PathBuf,
    pub config: PathBuf,
    pub project: PathBuf,
    pub session: String,
}

impl Env {
    pub fn new() -> Env {
        let dir = tempfile::tempdir().expect("tempdir");
        let home = dir.path().join("home");
        let config = dir.path().join("claude");
        let project = dir.path().join("project");
        for p in [&home, &config, &project] {
            std::fs::create_dir_all(p).expect("create dir");
        }
        Env {
            dir,
            home,
            config,
            project,
            session: "test-session".to_string(),
        }
    }

    pub fn settings_path(&self) -> PathBuf {
        self.config.join("settings.json")
    }

    pub fn db_path(&self) -> PathBuf {
        self.home.join("velra.db")
    }

    pub fn spool_dir(&self) -> PathBuf {
        self.home.join("spool")
    }

    /// A connection for assertions. The busy timeout is set explicitly rather
    /// than inherited from the role so that a test never reports `Busy` while
    /// a reduce or a hook still holds the write lock.
    pub fn open_db(&self) -> Db {
        let db = Db::open(&self.db_path(), Role::Cli).expect("open db");
        db.conn
            .busy_timeout(TEST_BUSY_TIMEOUT)
            .expect("busy timeout");
        db
    }

    pub fn project_id(&self) -> String {
        let canonical = paths::canonical(&self.project).unwrap_or_else(|| self.project.clone());
        let normalized = paths::normalize_abs(&canonical.to_string_lossy());
        hash::hex_prefix(paths::identity(&normalized).as_bytes(), 16)
    }

    pub fn project_info(&self) -> ProjectInfo {
        let canonical = paths::canonical(&self.project).unwrap_or_else(|| self.project.clone());
        ProjectInfo {
            project_id: self.project_id(),
            root_path: paths::normalize_abs(&canonical.to_string_lossy()),
            is_git: self.project.join(".git").exists(),
        }
    }

    /// The `velra` binary with this environment applied.
    pub fn cmd(&self) -> Command {
        let mut cmd = Command::cargo_bin("velra").expect("binary");
        cmd.env("VELRA_HOME", &self.home)
            .env("CLAUDE_CONFIG_DIR", &self.config)
            .env("CLAUDE_PROJECT_DIR", &self.project)
            .env("TZ", "UTC")
            .env_remove("VELRA_DISABLE")
            .env_remove("VELRA_LOG")
            .env_remove("VELRA_TEST_PANIC")
            .env_remove("VELRA_TEST_STALL_MS")
            // Never race the production deadline on a shared runner.
            .env("VELRA_TEST_WATCHDOG_MS", TEST_WATCHDOG_MS)
            .current_dir(&self.project);
        cmd
    }

    /// `cmd` with the production watchdog restored, for the tests that measure
    /// the deadline itself rather than what the hook records.
    pub fn cmd_with_real_watchdog(&self) -> Command {
        let mut cmd = self.cmd();
        cmd.env_remove("VELRA_TEST_WATCHDOG_MS");
        cmd
    }

    /// Runs one hook with the given stdin payload.
    pub fn hook(&self, event: &str, payload: &Value) -> HookOutput {
        self.hook_raw(event, payload.to_string().as_bytes())
    }

    /// Runs one hook with extra environment variables, for a test that needs to
    /// take the watchdog out of play (`VELRA_TEST_WATCHDOG_MS`, which the binary
    /// honours only under the `fault-injection` feature).
    pub fn hook_with_env(&self, event: &str, payload: &Value, vars: &[(&str, &str)]) -> HookOutput {
        self.hook_raw_with_env(event, payload.to_string().as_bytes(), vars)
    }

    pub fn hook_raw(&self, event: &str, stdin: &[u8]) -> HookOutput {
        self.hook_raw_with_env(event, stdin, &[])
    }

    /// `hook_with_env` for stdin that is deliberately not valid JSON.
    pub fn hook_raw_with_env(
        &self,
        event: &str,
        stdin: &[u8],
        vars: &[(&str, &str)],
    ) -> HookOutput {
        let mut cmd = self.cmd();
        for (key, value) in vars {
            cmd.env(key, value);
        }
        let out = cmd
            .arg("hook")
            .arg(event)
            .write_stdin(stdin.to_vec())
            .output()
            .expect("run hook");
        HookOutput {
            code: out.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
        }
    }

    pub fn reduce(&self) -> HookOutput {
        let out = self
            .cmd()
            .arg("reduce")
            .write_stdin("{}")
            .output()
            .expect("run reduce");
        HookOutput {
            code: out.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
        }
    }

    /// Ingests whatever the hooks left in the spool (§10.3). The engine's
    /// guarantee is that an event reaches the database *or* the spool, so a
    /// query that has not drained is asking only half the question.
    pub fn drain(&self) {
        self.reduce().assert_contract();
    }

    /// `drain` followed by `query`, retried until `settled` accepts the result
    /// or `DRAIN_TIMEOUT` expires. The last result is returned either way, so
    /// the caller's own assertion is what reports the failure.
    ///
    /// The retry is what absorbs runner latency: a spool file written as the
    /// hook exits, an NTFS page not yet visible to the next reader, a lock
    /// handed over between processes.
    pub fn drain_and_query<T>(&self, settled: impl Fn(&T) -> bool, query: impl Fn(&Db) -> T) -> T {
        let deadline = Instant::now() + DRAIN_TIMEOUT;
        loop {
            self.drain();
            let value = query(&self.open_db());
            if settled(&value) || Instant::now() >= deadline {
                return value;
            }
            std::thread::sleep(DRAIN_POLL);
        }
    }

    /// Every row of `events` in id order, once at least `at_least` of them are
    /// visible. Waiting for a count rather than for any row at all keeps a test
    /// that expects several events from reading a partially ingested log.
    pub fn drain_and_load_events(&self, at_least: usize) -> Vec<TestEvent> {
        self.drain_and_query(
            |rows: &Vec<TestEvent>| rows.len() >= at_least,
            |db| {
                db.conn
                    .prepare("SELECT hook_event, tool_name, payload FROM events ORDER BY id")
                    .expect("prepare")
                    .query_map([], |r| {
                        Ok(TestEvent {
                            hook_event: r.get(0)?,
                            tool_name: r.get(1)?,
                            payload: r.get(2)?,
                        })
                    })
                    .expect("query")
                    .collect::<Result<_, _>>()
                    .expect("rows")
            },
        )
    }

    /// Asserts the exact contents of `events`, once the spool is drained.
    pub fn assert_event_count(&self, expected: usize) -> Vec<TestEvent> {
        let rows = self.drain_and_load_events(expected);
        assert_eq!(rows.len(), expected, "events: {rows:#?}");
        rows
    }

    /// Common hook input fields.
    pub fn base_payload(&self, event: &str) -> Value {
        json!({
            "session_id": self.session,
            "hook_event_name": event,
            "cwd": self.project.to_string_lossy(),
            "transcript_path": self.dir.path().join("transcript.jsonl").to_string_lossy(),
        })
    }

    pub fn write_file(&self, rel: &str, content: &str) -> PathBuf {
        let path = self.project.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("create parent");
        }
        std::fs::write(&path, content).expect("write file");
        path
    }

    /// Creates a minimal git repository (no `git` binary involved).
    pub fn init_git(&self, branch: &str, sha: &str) {
        let git = self.project.join(".git");
        std::fs::create_dir_all(git.join("refs/heads")).expect("git dirs");
        std::fs::write(git.join("HEAD"), format!("ref: refs/heads/{branch}\n")).expect("HEAD");
        // Branch names may contain slashes (`feat/auth-refactor`), so the ref
        // file lives one or more directories deep.
        let ref_path = git.join(format!("refs/heads/{branch}"));
        if let Some(parent) = ref_path.parent() {
            std::fs::create_dir_all(parent).expect("ref dirs");
        }
        std::fs::write(&ref_path, format!("{sha}\n")).expect("ref");
    }
}

/// One row of `events`, in the shape the assertions in this suite read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestEvent {
    pub hook_event: String,
    pub tool_name: Option<String>,
    pub payload: String,
}

impl TestEvent {
    /// The payload parsed as JSON.
    pub fn json(&self) -> Value {
        serde_json::from_str(&self.payload).expect("payload json")
    }

    /// What the event is filed under: its tool name, or its hook event when it
    /// has none.
    pub fn label(&self) -> &str {
        self.tool_name.as_deref().unwrap_or(&self.hook_event)
    }
}

pub struct HookOutput {
    pub code: i32,
    pub stdout: String,
    pub stderr: String,
}

impl HookOutput {
    /// §8.1: exit 0, empty stderr, stdout empty or exactly one JSON object
    /// on a single line followed by `\n`.
    pub fn assert_contract(&self) -> &Self {
        assert_eq!(self.code, 0, "exit code must be 0, stderr: {}", self.stderr);
        assert!(
            self.stderr.is_empty(),
            "stderr must be empty, got: {}",
            self.stderr
        );
        if !self.stdout.is_empty() {
            assert!(
                self.stdout.ends_with('\n'),
                "stdout must end with a newline"
            );
            let line = self.stdout.trim_end_matches('\n');
            assert!(!line.contains('\n'), "stdout must be a single line");
            let value: Value = serde_json::from_str(line).expect("stdout must be one JSON object");
            assert!(value.is_object(), "stdout must be a JSON object");
        }
        self
    }

    pub fn json(&self) -> Option<Value> {
        serde_json::from_str(self.stdout.trim_end_matches('\n')).ok()
    }
}

/// Builds an event log directly, without going through the hook binary.
pub struct Log {
    pub env: Env,
    pub db: Db,
    pub ts: i64,
    seq: usize,
}

impl Log {
    pub fn new() -> Log {
        let env = Env::new();
        let db = env.open_db();
        Log {
            env,
            db,
            ts: BASE_MS,
            seq: 0,
        }
    }

    /// Closes the setup connection and hands back the `Env`.
    ///
    /// `Env` owns the temp dir, so dropping a whole `Log` deletes the database
    /// along with it. A test that wants to reopen the database itself — say to
    /// race several connections against it — needs the directory to outlive
    /// that first connection.
    pub fn into_env(self) -> Env {
        self.env
    }

    fn next(&mut self) -> (i64, String) {
        self.ts += 1_000;
        self.seq += 1;
        (self.ts, format!("toolu_{:04}", self.seq))
    }

    pub fn append(&mut self, hook_event: &str, tool: Option<&str>, payload: Payload) -> i64 {
        self.append_as(hook_event, tool, payload, None)
    }

    pub fn append_as(
        &mut self,
        hook_event: &str,
        tool: Option<&str>,
        payload: Payload,
        agent: Option<&str>,
    ) -> i64 {
        let (ts, tool_use_id) = self.next();
        let session = self.env.session.clone();
        let ev = NewEvent {
            dedupe_key: dedupe_key(hook_event, &session, Some(&tool_use_id), None, ts, agent),
            session_id: session,
            project_id: self.env.project_id(),
            agent_id: agent.map(str::to_string),
            hook_event: hook_event.to_string(),
            tool_name: tool.map(str::to_string),
            tool_use_id: Some(tool_use_id),
            ts_ms: ts,
            payload: payload.to_json(),
            project: Some(self.env.project_info()),
        };
        eventlog::append(&mut self.db.conn, &ev)
            .expect("append")
            .unwrap_or(0)
    }

    /// Appends an event carrying `ts_ms` instead of the log's own clock.
    ///
    /// This is the shape a spooled event takes: the hook stamped it when it
    /// happened, could not reach the database, wrote it to the spool, and the
    /// reducer ingested it later — so it lands with an old timestamp and a row
    /// id newer than events that really came after it.
    pub fn append_late(
        &mut self,
        hook_event: &str,
        tool: Option<&str>,
        payload: Payload,
        ts_ms: i64,
    ) -> i64 {
        self.seq += 1;
        let tool_use_id = format!("toolu_late_{:04}", self.seq);
        let session = self.env.session.clone();
        let ev = NewEvent {
            dedupe_key: dedupe_key(hook_event, &session, Some(&tool_use_id), None, ts_ms, None),
            session_id: session,
            project_id: self.env.project_id(),
            agent_id: None,
            hook_event: hook_event.to_string(),
            tool_name: tool.map(str::to_string),
            tool_use_id: Some(tool_use_id),
            ts_ms,
            payload: payload.to_json(),
            project: Some(self.env.project_info()),
        };
        eventlog::append(&mut self.db.conn, &ev)
            .expect("append")
            .unwrap_or(0)
    }

    /// Hashes the files as they are on disk right now, as a hook would.
    pub fn observe(&self, rels: &[&str]) -> Vec<velra_core::event::FileObservation> {
        rels.iter()
            .map(|rel| {
                let (h, size) = hash::hash_file(&self.env.project.join(rel));
                velra_core::event::FileObservation {
                    path: rel.to_string(),
                    hash: h,
                    size,
                }
            })
            .collect()
    }

    pub fn prompt(&mut self, text: &str) {
        self.append(
            "UserPromptSubmit",
            None,
            Payload {
                prompt: Some(text.into()),
                ..Default::default()
            },
        );
    }

    /// A full edit: pre-hash, file change on disk, post-hash.
    pub fn edit(&mut self, rel: &str, new_content: &str) {
        self.edit_with(rel, new_content, "Edit", None)
    }

    pub fn edit_as(&mut self, rel: &str, new_content: &str, agent: &str) {
        self.edit_with(rel, new_content, "Edit", Some(agent))
    }

    pub fn write_tool(&mut self, rel: &str, new_content: &str) {
        self.edit_with(rel, new_content, "Write", None)
    }

    fn edit_with(&mut self, rel: &str, new_content: &str, tool: &str, agent: Option<&str>) {
        let abs = self.env.project.join(rel);
        let old = std::fs::read_to_string(&abs).unwrap_or_default();
        let (pre_hash, pre_size) = hash::hash_file(&abs);
        self.append_as(
            "PreToolUse",
            Some(tool),
            Payload {
                path: Some(rel.into()),
                pre_hash: Some(pre_hash),
                size: Some(pre_size),
                ..Default::default()
            },
            agent,
        );
        self.env.write_file(rel, new_content);
        let (post_hash, size) = hash::hash_file(&abs);
        let excerpt = first_diff_line(&old, new_content);
        self.append_as(
            "PostToolUse",
            Some(tool),
            Payload {
                path: Some(rel.into()),
                post_hash: Some(post_hash),
                size: Some(size),
                lines_added: Some(new_content.lines().count() as u32),
                lines_removed: if tool == "Write" {
                    None
                } else {
                    Some(old.lines().count() as u32)
                },
                excerpt,
                ..Default::default()
            },
            agent,
        );
    }

    pub fn read(&mut self, rel: &str) {
        self.append(
            "PostToolUse",
            Some("Read"),
            Payload {
                path: Some(rel.into()),
                ..Default::default()
            },
        );
    }

    /// A shell command that succeeded.
    pub fn command_ok(&mut self, command: &str, stdout: &str) {
        self.append(
            "PostToolUse",
            Some("Bash"),
            Payload {
                command: Some(command.into()),
                cwd: Some(self.env.project.to_string_lossy().into_owned()),
                stdout_tail: Some(stdout.into()),
                ..Default::default()
            },
        );
    }

    /// A shell command that failed (`PostToolUseFailure` with `Exit code N`).
    pub fn command_fail(&mut self, command: &str, exit: i64, output: &str) {
        self.append(
            "PostToolUseFailure",
            Some("Bash"),
            Payload {
                command: Some(command.into()),
                cwd: Some(self.env.project.to_string_lossy().into_owned()),
                error: Some(format!("Exit code {exit}\n{output}")),
                is_interrupt: Some(false),
                tool_name: Some("Bash".into()),
                ..Default::default()
            },
        );
    }

    /// A git restore-family command: hashes before, file change, hashes after.
    pub fn git_restore(&mut self, command: &str, changes: &[(&str, &str)]) {
        self.git_command(command, changes, true, false)
    }

    /// A restore-family command reported as a *failed* tool call, which is what
    /// Claude Code sends for `git restore x && pytest` whenever the suite still
    /// fails afterwards.
    pub fn git_restore_failed(
        &mut self,
        command: &str,
        exit: i64,
        output: &str,
        changes: &[(&str, &str)],
    ) {
        self.git_command_with(command, changes, true, false, Some((exit, output)))
    }

    pub fn git_commit(&mut self, command: &str, files: &[&str]) {
        let changes: Vec<(&str, &str)> = files.iter().map(|f| (*f, "")).collect();
        self.git_command(command, &changes, false, true)
    }

    /// A commit reported as a failed tool call.
    pub fn git_commit_failed(&mut self, command: &str, exit: i64, output: &str, files: &[&str]) {
        let changes: Vec<(&str, &str)> = files.iter().map(|f| (*f, "")).collect();
        self.git_command_with(command, &changes, false, true, Some((exit, output)))
    }

    fn git_command(
        &mut self,
        command: &str,
        changes: &[(&str, &str)],
        restore: bool,
        commit: bool,
    ) {
        self.git_command_with(command, changes, restore, commit, None)
    }

    fn git_command_with(
        &mut self,
        command: &str,
        changes: &[(&str, &str)],
        restore: bool,
        commit: bool,
        failure: Option<(i64, &str)>,
    ) {
        let observe = |env: &Env, rel: &str| {
            let (h, size) = hash::hash_file(&env.project.join(rel));
            velra_core::event::FileObservation {
                path: rel.to_string(),
                hash: h,
                size,
            }
        };
        // The hook records the restore-family *subcommand*, not the whole line
        // it was chained into; mirror that here or the harness tests something
        // the product never produces.
        let restore = restore
            .then(|| velra_core::shell::git_effects(command, &|_| false).restore)
            .flatten()
            .or_else(|| restore.then(|| command.to_string()));
        let pre: Vec<_> = changes
            .iter()
            .map(|(rel, _)| observe(&self.env, rel))
            .collect();
        self.append(
            "PreToolUse",
            Some("Bash"),
            Payload {
                command: Some(command.into()),
                git: Some(velra_core::event::GitObservation {
                    restore: restore.clone(),
                    commit,
                    files: pre,
                }),
                ..Default::default()
            },
        );
        for (rel, content) in changes {
            if !content.is_empty() {
                self.env.write_file(rel, content);
            }
        }
        let post: Vec<_> = changes
            .iter()
            .map(|(rel, _)| observe(&self.env, rel))
            .collect();
        let git = Some(velra_core::event::GitObservation {
            restore,
            commit,
            files: post,
        });
        match failure {
            None => self.append(
                "PostToolUse",
                Some("Bash"),
                Payload {
                    command: Some(command.into()),
                    cwd: Some(self.env.project.to_string_lossy().into_owned()),
                    stdout_tail: Some(String::new()),
                    git,
                    ..Default::default()
                },
            ),
            Some((exit, output)) => self.append(
                "PostToolUseFailure",
                Some("Bash"),
                Payload {
                    command: Some(command.into()),
                    cwd: Some(self.env.project.to_string_lossy().into_owned()),
                    error: Some(format!("Exit code {exit}\n{output}")),
                    is_interrupt: Some(false),
                    tool_name: Some("Bash".into()),
                    git,
                    ..Default::default()
                },
            ),
        };
    }

    pub fn stop(&mut self) {
        self.append(
            "Stop",
            None,
            Payload {
                stop_hook_active: Some(false),
                ..Default::default()
            },
        );
    }

    pub fn reduce(&mut self) {
        reducer::reduce_all(&mut self.db.conn, Some(&self.env.spool_dir())).expect("reduce");
    }

    pub fn snapshot(&mut self) -> Snapshot {
        self.reduce();
        let meta = SnapshotMeta {
            checkpoint_id: "ckpt_01TESTFIXTURE0000000000000".to_string(),
            created_ms: self.ts + 1_000,
            trigger: Trigger::Manual,
            partial: false,
            preview: false,
            tz_offset_secs: 0,
        };
        velra_core::snapshot::build(&self.db.conn, &self.env.session.clone(), &meta)
            .expect("snapshot")
    }

    pub fn capsule(&mut self) -> String {
        let snap = self.snapshot();
        velra_core::render::render(&snap, &RenderConfig::default()).text
    }

    /// Renders at an explicit budget.
    ///
    /// The shipped default is deliberately below the spec's 800 to absorb the
    /// estimator's error (see `render::DEFAULT_BUDGET_TOKENS`). Tests about
    /// *what the ladder keeps* rather than *what the default trims* pin the
    /// spec figure here, so they keep testing section coverage instead of
    /// silently becoming tests of the margin.
    pub fn capsule_at(&mut self, budget_tokens: u32) -> String {
        let snap = self.snapshot();
        velra_core::render::render(&snap, &RenderConfig { budget_tokens }).text
    }

    /// Creates a checkpoint the way `pre-compact` does.
    pub fn checkpoint(&mut self) -> String {
        self.reduce();
        let session = self.env.session.clone();
        let created = self.ts + 1_000;
        let tx = self.db.conn.transaction().expect("tx");
        let info = checkpoint::create_in_tx(
            &tx,
            &CheckpointRequest {
                session_id: &session,
                trigger: Trigger::Manual,
                created_ms: created,
                partial: false,
                watermark: 0,
            },
            &RenderConfig::default(),
        )
        .expect("checkpoint")
        .expect("something worth saving");
        tx.commit().expect("commit");
        info.checkpoint_id
    }

    pub fn edits(&self) -> Vec<(String, String, Option<String>)> {
        let mut stmt = self
            .db
            .conn
            .prepare("SELECT path, status, mechanism FROM edits ORDER BY id")
            .expect("prepare");
        let rows = stmt
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
            .expect("query")
            .collect::<Result<Vec<_>, _>>()
            .expect("rows");
        rows
    }

    pub fn dead_ends(&self) -> Vec<(String, String, Option<String>, i64)> {
        let mut stmt = self
            .db
            .conn
            .prepare("SELECT path, mechanism, command_text, reapplied FROM dead_ends ORDER BY id")
            .expect("prepare");
        stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
            .expect("query")
            .collect::<Result<Vec<_>, _>>()
            .expect("rows")
    }

    pub fn versions(&self, path: &str) -> Vec<(String, String)> {
        let mut stmt = self
            .db
            .conn
            .prepare("SELECT source, content_hash FROM file_versions WHERE path = ?1 ORDER BY id")
            .expect("prepare");
        stmt.query_map([path], |r| Ok((r.get(0)?, r.get(1)?)))
            .expect("query")
            .collect::<Result<Vec<_>, _>>()
            .expect("rows")
    }

    pub fn commands(&self) -> Vec<(String, String, String)> {
        let mut stmt = self
            .db
            .conn
            .prepare("SELECT kind, outcome, command_text FROM commands ORDER BY id")
            .expect("prepare");
        stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
            .expect("query")
            .collect::<Result<Vec<_>, _>>()
            .expect("rows")
    }
}

fn first_diff_line(old: &str, new: &str) -> Option<String> {
    let mut o = old.lines();
    let mut n = new.lines();
    loop {
        match (o.next(), n.next()) {
            (Some(a), Some(b)) if a == b => continue,
            (None, None) => return None,
            (a, b) => {
                let mut out = String::new();
                if let Some(a) = a.map(str::trim).filter(|s| !s.is_empty()) {
                    out.push_str(&format!("- {a}"));
                }
                if let Some(b) = b.map(str::trim).filter(|s| !s.is_empty()) {
                    if !out.is_empty() {
                        out.push('\n');
                    }
                    out.push_str(&format!("+ {b}"));
                }
                return (!out.is_empty()).then_some(out);
            }
        }
    }
}

/// Snapshot settings so golden capsules live in `tests/golden/capsule`.
pub fn golden_capsule(name: &str, text: &str) {
    let mut settings = insta::Settings::clone_current();
    settings.set_snapshot_path("../../../../tests/golden/capsule");
    settings.set_prepend_module_to_snapshot(false);
    settings.bind(|| insta::assert_snapshot!(name, text));
}