mindfork 0.10.2

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
//! What the assistant changed in the attached project, as a diff the changes
//! screen can draw — and putting one file back (spec §9.12,
//! [docs/history/code-workspace.md](../../docs/history/code-workspace.md) §3.5).
//!
//! The input is the change journal (`features/workspace_journal.rs`): the bytes
//! of every file as it stood **before** the assistant first touched it in this
//! chat. Against the file as it stands now, that is the answer to "what did the
//! assistant do" — which is deliberately not "what differs from HEAD": an
//! attached directory need not be a repository, and a repository routinely
//! carries the user's own uncommitted work.
//!
//! **The diff is built here, not in the screen.** The plan sketched a screen
//! that diffs the selected file lazily from baseline and current text; the
//! codebase's own rule is stronger and cheaper — a screen is a pure projection
//! of a snapshot the orchestrator built off the runtime (the message-search
//! screen says so in as many words). It also decides the size of the event: a
//! rendered diff is a fraction of the two files it came from, and it is computed
//! once instead of on every `↑`.
//!
//! Everything that can go wrong with a file is a **state**, not an error: gone,
//! binary, too large, unchanged after all. Each of those has a different next
//! move for the user, so each says which it is rather than showing an empty
//! diff (docs/lessons.md §4).

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use crate::features::workspace_journal::Journal;

/// Files past this are described rather than diffed. A diff of a megabyte of
/// text is not something anyone reads in a terminal pane, and building it would
/// stall the frame it is drawn in.
const MAX_DIFF_BYTES: u64 = 1024 * 1024;

/// How many unchanged lines surround each hunk.
const CONTEXT_LINES: usize = 3;

/// What one line of a rendered diff is, so the screen colours it without
/// re-parsing the text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffKind {
    /// `@@ … @@` — where in the file the next lines are.
    Hunk,
    /// A line both versions have.
    Context,
    Added,
    Removed,
}

/// One line of a rendered diff.
#[derive(Debug, Clone, PartialEq)]
pub struct DiffLine {
    pub kind: DiffKind,
    /// The text **without** its `+`/`-`/space marker: the screen draws the
    /// marker itself, in the colour that goes with it, and a marker baked into
    /// the string would be indistinguishable from a `+` the file's own line
    /// starts with.
    pub text: String,
}

/// What became of a journaled file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileState {
    /// It existed and was changed.
    Modified,
    /// The assistant created it — reverting deletes it.
    Created,
    /// Journaled, but it is not on disk now. Nothing here can delete a file, so
    /// this is the user's own doing (or a revert that already happened), and
    /// saying so beats showing the whole file as removed.
    Gone,
    /// Binary, or larger than [`MAX_DIFF_BYTES`]: no diff, but the revert still
    /// works — it is a byte copy either way.
    NotShown,
    /// Touched, then put back to exactly what it was. Kept in the list rather
    /// than hidden: "I changed it and changed it back" is an answer, and a file
    /// vanishing from the list would look like the journal lost it.
    Unchanged,
}

/// One file of the change set.
#[derive(Debug, Clone, PartialEq)]
pub struct FileChange {
    /// Project-relative, forward slashes — the spelling the tools use.
    pub path: String,
    pub state: FileState,
    pub added: usize,
    pub removed: usize,
    pub lines: Vec<DiffLine>,
}

/// Everything the assistant changed in this chat's project.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ChangeSet {
    /// The project root, for the screen's title. Empty when nothing is
    /// journaled and there is no root to name.
    pub root: String,
    pub files: Vec<FileChange>,
}

impl ChangeSet {
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }
}

/// Builds the change set for one chat: every journaled file, diffed against what
/// is on disk now.
///
/// Blocking file I/O — the caller runs it off the async runtime. `hint` is the encoding
/// detector's, the interface language's TLD — what the tools that wrote the files had.
pub fn build(journal_dir: &Path, root: &str, hint: Option<&str>) -> ChangeSet {
    let journal = Journal::new(journal_dir.to_path_buf());
    // The journal is the chat's, `root` is the chat's *current* workspace, and
    // `/project attach` moves the second. It clears the journal when it does —
    // but the guard lives here as well, because the invariant belongs to
    // whoever reads the baselines, not to whoever happens to write the
    // workspace field (design fork F13). "Nothing changed in *this* project" is
    // the truthful answer and the one that cannot revert into the wrong tree.
    if !journal.describes(root) {
        return ChangeSet {
            root: root.to_string(),
            files: Vec::new(),
        };
    }
    let files = journal
        .entries()
        .into_iter()
        .map(|entry| {
            let baseline = journal.baseline_of(&entry.path).unwrap_or_default();
            diff_file(root, &entry.path, entry.existed, &baseline, hint)
        })
        .collect();
    ChangeSet {
        root: root.to_string(),
        files,
    }
}

/// Resolves a project-relative path against the root.
///
/// The journal only ever holds paths the tools produced, which are already
/// confined — but this reads and *writes* the user's files, so it re-checks
/// rather than trusting a stored string: a guard that assumes its input is
/// clean is one edited `manifest.json` from being no guard at all.
fn resolve(root: &str, rel: &str) -> Option<PathBuf> {
    let root = PathBuf::from(root).canonicalize().ok()?;
    let joined = root.join(rel);
    // The file may be gone, so the path itself need not canonicalize; what has
    // to hold is that no component climbs out.
    if joined
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        return None;
    }
    joined.starts_with(&root).then_some(joined)
}

/// One file's row: its state, its counts and its rendered diff.
fn diff_file(
    root: &str,
    rel: &str,
    existed: bool,
    baseline: &[u8],
    hint: Option<&str>,
) -> FileChange {
    use crate::shared::text_decode;
    let row = |state: FileState, lines: Vec<DiffLine>| FileChange {
        path: rel.to_string(),
        state,
        added: 0,
        removed: 0,
        lines,
    };
    let Some(path) = resolve(root, rel) else {
        return row(FileState::Gone, Vec::new());
    };
    let Ok(current) = std::fs::read(&path) else {
        return row(FileState::Gone, Vec::new());
    };
    let too_large = current.len() as u64 > MAX_DIFF_BYTES || baseline.len() as u64 > MAX_DIFF_BYTES;
    // Text by the rule the tools read with — a NUL is binary unless the file is whole
    // UTF-16 — and both sides in the current file's encoding, so a byte change reads as a
    // text change (docs/research/local-file-encoding.md §3).
    let markup = text_decode::is_markup_path(&path);
    let current_file = (!too_large)
        .then(|| text_decode::decode_file(&current, markup, hint))
        .flatten()
        .filter(|_| text_decode::decode_file(baseline, markup, hint).is_some());
    let Some(current_file) = current_file else {
        return row(FileState::NotShown, Vec::new());
    };
    // Normalized to `\n` on both sides, for the reason the editing tools
    // normalize: a CRLF checkout would otherwise show every line as changed.
    let before = current_file
        .encoding
        .decode_with_bom_removal(baseline)
        .0
        .replace("\r\n", "\n");
    let after = current_file.text.replace("\r\n", "\n");
    if before == after {
        if !same_file(baseline, &current, current_file.encoding) {
            // A byte the encoding cannot read decodes to U+FFFD on both sides, whatever it
            // was: equal text over different bytes is a change this screen cannot draw, and
            // calling it unchanged is how the screen once hid a rewritten file (research §1).
            let state = if existed {
                FileState::Modified
            } else {
                FileState::Created
            };
            return row(state, Vec::new());
        }
        let state = if existed {
            FileState::Unchanged
        } else {
            // Created, and the "baseline" is emptiness: an empty file the
            // assistant created really is unchanged against it, and calling
            // that "unchanged" would hide that the file is new.
            FileState::Created
        };
        return row(state, Vec::new());
    }
    let (lines, added, removed) = render(&before, &after);
    FileChange {
        path: rel.to_string(),
        state: if existed {
            FileState::Modified
        } else {
            FileState::Created
        },
        added,
        removed,
        lines,
    }
}

/// Whether two versions whose texts read alike are the same file: byte for byte, or both
/// read without loss in `encoding` — so that equal text is equal content, line endings
/// aside (spec §9.12: line endings alone are not a change).
fn same_file(baseline: &[u8], current: &[u8], encoding: &'static encoding_rs::Encoding) -> bool {
    use crate::shared::text_decode;
    let bom = text_decode::bom_of(encoding);
    let lossless =
        |bytes: &[u8]| text_decode::round_trips(bytes.strip_prefix(bom).unwrap_or(bytes), encoding);
    baseline == current || (lossless(baseline) && lossless(current))
}

/// Renders a unified diff into lines the screen can colour, plus the counts.
fn render(before: &str, after: &str) -> (Vec<DiffLine>, usize, usize) {
    use similar::{ChangeTag, TextDiff};

    let diff = TextDiff::from_lines(before, after);
    let mut lines = Vec::new();
    let (mut added, mut removed) = (0usize, 0usize);
    for (i, group) in diff.grouped_ops(CONTEXT_LINES).into_iter().enumerate() {
        if let (Some(first), Some(last)) = (group.first(), group.last()) {
            let (old, new) = (first.old_range().start, first.new_range().start);
            let (old_end, new_end) = (last.old_range().end, last.new_range().end);
            lines.push(DiffLine {
                kind: DiffKind::Hunk,
                text: format!(
                    "@@ -{},{} +{},{} @@",
                    old + 1,
                    old_end - old,
                    new + 1,
                    new_end - new
                ),
            });
        } else if i > 0 {
            continue;
        }
        for op in group {
            for change in diff.iter_changes(&op) {
                let kind = match change.tag() {
                    ChangeTag::Equal => DiffKind::Context,
                    ChangeTag::Insert => {
                        added += 1;
                        DiffKind::Added
                    }
                    ChangeTag::Delete => {
                        removed += 1;
                        DiffKind::Removed
                    }
                };
                lines.push(DiffLine {
                    kind,
                    // The trailing newline is the line separator, not content:
                    // left in, it would draw an empty row after every line.
                    text: change.value().trim_end_matches('\n').to_string(),
                });
            }
        }
    }
    (lines, added, removed)
}

/// Puts one file back to its baseline and forgets it.
///
/// The two halves are one operation on purpose: a restored file still listed as
/// changed would offer a second revert that does nothing, and a forgotten entry
/// whose file was not restored loses the bytes for good. The write happens
/// first — if it fails, the journal still holds the baseline and the user can
/// try again.
pub fn revert(journal_dir: &Path, root: &str, rel: &str) -> Result<()> {
    let journal = Journal::new(journal_dir.to_path_buf());
    // Same guard as `build`, and here it is the one that matters: this writes
    // the user's files. Refusing rather than answering empty, because a revert
    // is an action and a silent no-op reads as "done" (docs/lessons.md §4).
    anyhow::ensure!(
        journal.describes(root),
        "this chat's change journal belongs to another project — nothing was written"
    );
    let entry = journal
        .entries()
        .into_iter()
        .find(|e| e.path == rel)
        .with_context(|| format!("{rel} is not in this chat's change journal"))?;
    let path = resolve(root, rel).with_context(|| format!("{rel} is outside {root}"))?;
    if entry.existed {
        let baseline = journal
            .baseline_of(rel)
            .with_context(|| format!("the stored original of {rel} is missing"))?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
        }
        std::fs::write(&path, &baseline)
            .with_context(|| format!("restoring {}", path.display()))?;
    } else if path.exists() {
        // The assistant created it, so putting it back means removing it. A
        // file already gone is not an error — the end state is what was asked
        // for.
        std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
    }
    journal.forget(rel)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A project directory, a journal directory, and a `Journal` over it.
    struct Fixture {
        _dir: tempfile::TempDir,
        root: PathBuf,
        journal_dir: PathBuf,
    }

    impl Fixture {
        fn new() -> Self {
            let dir = tempfile::tempdir().unwrap();
            let root = dir.path().join("proj");
            std::fs::create_dir_all(&root).unwrap();
            let journal_dir = dir.path().join("journal");
            Self {
                _dir: dir,
                root,
                journal_dir,
            }
        }

        fn root(&self) -> String {
            self.root.to_string_lossy().into_owned()
        }

        fn journal(&self) -> Journal {
            Journal::new(self.journal_dir.clone())
        }

        /// Writes `before` (or nothing), journals it, then writes `after` (or
        /// removes the file) — the assistant's edit, reproduced.
        fn touched(&self, rel: &str, before: Option<&str>, after: Option<&str>) {
            let path = self.root.join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            if let Some(before) = before {
                std::fs::write(&path, before).unwrap();
            }
            self.journal()
                .record(&self.root(), rel, before.map(str::as_bytes))
                .unwrap();
            match after {
                Some(after) => std::fs::write(&path, after).unwrap(),
                None => {
                    let _ = std::fs::remove_file(&path);
                }
            }
        }

        fn build(&self) -> ChangeSet {
            build(&self.journal_dir, &self.root(), None)
        }
    }

    /// Journals `before` and leaves `after` on disk, as raw bytes — what
    /// [`Fixture::touched`], which takes text, cannot write.
    fn touched_bytes(f: &Fixture, rel: &str, before: &[u8], after: &[u8]) {
        let path = f.root.join(rel);
        std::fs::write(&path, before).unwrap();
        f.journal().record(&f.root(), rel, Some(before)).unwrap();
        std::fs::write(&path, after).unwrap();
    }

    /// A windows-1251 file's diff reads in its own encoding: one line changed, and the
    /// line around it Russian rather than replacement characters.
    #[test]
    fn a_legacy_file_is_diffed_in_its_own_encoding() {
        let f = Fixture::new();
        let cp1251 = |t: &str| encoding_rs::WINDOWS_1251.encode(t).0.into_owned();
        let text = "// Скидка растёт с каждым десятым заказом покупателя.\nlet x = 10;\n";
        touched_bytes(&f, "a.rs", &cp1251(text), &cp1251(&text.replace("10", "5")));
        let set = build(&f.journal_dir, &f.root(), Some("ru"));
        let file = &set.files[0];
        assert_eq!(
            (file.state, file.added, file.removed),
            (FileState::Modified, 1, 1)
        );
        assert!(
            file.lines.iter().any(|l| l.text.contains("Скидка растёт")),
            "{:?}",
            file.lines
        );
    }

    /// Equal text over different bytes is a change: an invalid byte reads as `U+FFFD`
    /// whatever it was, which is how a whole rewritten file once showed as one line
    /// (docs/research/local-file-encoding.md §1).
    #[test]
    fn a_byte_change_the_text_cannot_show_is_still_a_change() {
        let f = Fixture::new();
        let text = "// Скидка ".as_bytes();
        touched_bytes(
            &f,
            "a.rs",
            &[text, &[0xFF], b"\n"].concat(),
            &[text, &[0xFE], b"\n"].concat(),
        );
        assert_eq!(f.build().files[0].state, FileState::Modified);
    }

    #[test]
    fn a_changed_file_is_diffed_with_counts() {
        let f = Fixture::new();
        f.touched(
            "src/a.rs",
            Some("one\ntwo\nthree\n"),
            Some("one\n2\nthree\n"),
        );
        let set = f.build();
        assert_eq!(set.files.len(), 1);
        let file = &set.files[0];
        assert_eq!(file.path, "src/a.rs");
        assert_eq!(file.state, FileState::Modified);
        assert_eq!((file.added, file.removed), (1, 1));
        assert!(
            file.lines.iter().any(|l| l.kind == DiffKind::Hunk),
            "a hunk header is what says where in the file this is: {:?}",
            file.lines
        );
        assert!(
            file.lines
                .iter()
                .any(|l| l.kind == DiffKind::Removed && l.text == "two")
        );
        assert!(
            file.lines
                .iter()
                .any(|l| l.kind == DiffKind::Added && l.text == "2")
        );
        // The marker is the screen's to draw: a line carrying its own `+` could
        // not be told from a line whose text starts with one.
        assert!(
            file.lines.iter().all(|l| !l.text.starts_with('+')),
            "{:?}",
            file.lines
        );
    }

    /// Each of these has a different next move for the user, so each has to be
    /// distinguishable — an empty diff for all of them would say nothing
    /// (docs/lessons.md §4). Looped over the states rather than four
    /// near-identical tests.
    #[test]
    fn every_state_is_reported_as_itself() {
        let f = Fixture::new();
        f.touched("created.rs", None, Some("fn main() {}\n"));
        f.touched("modified.rs", Some("a\n"), Some("b\n"));
        f.touched("gone.rs", Some("a\n"), None);
        f.touched("undone.rs", Some("same\n"), Some("same\n"));
        std::fs::write(f.root.join("binary.rs"), [0u8, 1, 2]).unwrap();
        f.journal()
            .record(&f.root(), "binary.rs", Some(&[0u8, 9]))
            .unwrap();

        let set = f.build();
        let state = |name: &str| {
            set.files
                .iter()
                .find(|c| c.path == name)
                .unwrap_or_else(|| panic!("{name} missing from {:?}", set.files))
                .state
        };
        assert_eq!(state("created.rs"), FileState::Created);
        assert_eq!(state("modified.rs"), FileState::Modified);
        assert_eq!(state("gone.rs"), FileState::Gone);
        assert_eq!(state("undone.rs"), FileState::Unchanged);
        assert_eq!(state("binary.rs"), FileState::NotShown);
    }

    /// A Windows checkout is CRLF and the model writes `\n`. Without
    /// normalization every line of every file would read as changed, and the
    /// screen would be useless on exactly the platform this app targets first.
    #[test]
    fn line_endings_alone_are_not_a_change() {
        let f = Fixture::new();
        f.touched("crlf.rs", Some("a\r\nb\r\n"), Some("a\nb\n"));
        let set = f.build();
        assert_eq!(set.files[0].state, FileState::Unchanged);
        assert_eq!((set.files[0].added, set.files[0].removed), (0, 0));
    }

    /// Reverting restores the bytes **and** drops the row: a file put back but
    /// still listed offers a second revert that does nothing.
    #[test]
    fn reverting_restores_the_original_and_forgets_it() {
        let f = Fixture::new();
        f.touched("src/a.rs", Some("original\n"), Some("changed\n"));
        revert(&f.journal_dir, &f.root(), "src/a.rs").unwrap();
        assert_eq!(
            std::fs::read_to_string(f.root.join("src/a.rs")).unwrap(),
            "original\n"
        );
        assert!(f.build().is_empty(), "the row must be gone too");
    }

    /// The one deletion that exists in v1: a file the assistant created has no
    /// bytes to restore, so putting it back means removing it.
    #[test]
    fn reverting_a_created_file_deletes_it() {
        let f = Fixture::new();
        f.touched("src/new.rs", None, Some("fn main() {}\n"));
        revert(&f.journal_dir, &f.root(), "src/new.rs").unwrap();
        assert!(!f.root.join("src/new.rs").exists());
        assert!(f.build().is_empty());
    }

    /// Reverting something that is not journaled must fail rather than touch a
    /// file: the journal is the whole of what this may write to.
    #[test]
    fn reverting_an_unjournaled_path_is_refused() {
        let f = Fixture::new();
        std::fs::write(f.root.join("untouched.rs"), "mine\n").unwrap();
        assert!(revert(&f.journal_dir, &f.root(), "untouched.rs").is_err());
        assert_eq!(
            std::fs::read_to_string(f.root.join("untouched.rs")).unwrap(),
            "mine\n"
        );
    }

    /// A `manifest.json` is a file on disk and can be edited by hand. Neither
    /// the diff nor the revert may follow a path out of the project — the same
    /// containment the tools apply, applied again where the bytes are written.
    #[test]
    fn a_path_escaping_the_root_is_refused() {
        let f = Fixture::new();
        let outside = f.root.parent().unwrap().join("secret.txt");
        std::fs::write(&outside, "not yours\n").unwrap();
        assert!(resolve(&f.root(), "../secret.txt").is_none());
        assert!(revert(&f.journal_dir, &f.root(), "../secret.txt").is_err());
        assert_eq!(std::fs::read_to_string(&outside).unwrap(), "not yours\n");
    }

    #[test]
    fn an_empty_journal_is_an_empty_change_set() {
        let f = Fixture::new();
        assert!(f.build().is_empty());
    }

    /// A journal belonging to **another** project is not read at all — neither
    /// to show a diff nor, above all, to write one back (design fork F13).
    ///
    /// The shape that made this worth a guard rather than a comment: two
    /// sibling repositories both have a `Cargo.toml`, so the stale row resolves
    /// against the new root instead of coming back `Gone`, and reverting it put
    /// the *first* project's bytes into the second one's file. Measured before
    /// the fix, which is why the assertions below name the bytes.
    #[test]
    fn another_projects_journal_is_neither_shown_nor_reverted() {
        let dir = tempfile::tempdir().unwrap();
        let journal_dir = dir.path().join("journal");

        // Project A: the assistant edited its Cargo.toml, so the pre-image is
        // journaled and the file on disk differs from it.
        let a = dir.path().join("a");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::write(a.join("Cargo.toml"), "name = \"a\"\n").unwrap();
        Journal::new(journal_dir.clone())
            .record(&a.to_string_lossy(), "Cargo.toml", Some(b"name = \"a\"\n"))
            .unwrap();
        std::fs::write(a.join("Cargo.toml"), "name = \"a-edited\"\n").unwrap();

        // Project B, attached to the same chat, with a file of the same name.
        let b = dir.path().join("b");
        std::fs::create_dir_all(&b).unwrap();
        let b_root = b.to_string_lossy().into_owned();
        std::fs::write(b.join("Cargo.toml"), "name = \"b\"\n").unwrap();

        assert!(
            build(&journal_dir, &b_root, None).is_empty(),
            "project A's rows must not be listed against project B's root"
        );
        assert!(
            revert(&journal_dir, &b_root, "Cargo.toml").is_err(),
            "and a revert must refuse rather than write"
        );
        assert_eq!(
            std::fs::read_to_string(b.join("Cargo.toml")).unwrap(),
            "name = \"b\"\n",
            "project B's file is untouched"
        );
    }
}