monochromatic-git-policy-cli 0.5.34

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! Recovery checks against real Git repositories: registration, discards with their notices, and resumption.

use super::*;
use crate::test_support::{dead_copy_owner, fixture, git, git_context, remove, repository};
use crate::worktree_copy_install_entry::InstalledPath;
use crate::worktree_copy_journal::{
    Journal, adopt_journal, create_journal, create_journal_for, ensure_journal_root, journal_root, read_pending_journals,
    write_journal,
};
use crate::worktree_copy_selection::CopySelection;
use crate::worktree_copy_stage::{new_stage_container, stage_ignored_snapshot};
use crate::worktree_copy_stage_claim::{claim_stage, claim_stage_for, stage_claims_exist};
use std::os::unix::fs::PermissionsExt;

/// A repository with an ignored `cache` file and a linked worktree at `topic` that the copy would fill.
fn linked_source(root: &Path) -> (PathBuf, PathBuf) {
    let source: PathBuf = repository(root, "source");
    std::fs::write(source.join(".gitignore"), b"cache/\n").expect("gitignore");
    std::fs::create_dir_all(source.join("cache")).expect("cache");
    std::fs::write(source.join("cache/data"), b"payload").expect("data");
    let topic: PathBuf = root.join("topic");
    git(
        source.as_path(),
        &[
            "worktree",
            "add",
            "--quiet",
            "-b",
            "topic",
            topic.to_str().expect("utf8"),
        ],
    );
    return (
        std::fs::canonicalize(source).expect("canonical source"),
        std::fs::canonicalize(topic).expect("canonical topic"),
    );
}

/// Creates a staged journal for a destination, as an interrupted copy would have left it.
fn staged_journal(source: &Path, destination: &Path) -> PendingJournal {
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let snapshot: StagedSnapshot =
        stage_ignored_snapshot(&git_context(), source, new_stage_container(destination).expect("container").as_path(), &[], &CopySelection::Ignored).expect("staged");
    return create_journal_for(common.as_path(), destination, &snapshot, &dead_copy_owner()).expect("journal");
}

/// A linked worktree of the repository is registered; a removed or re-pointed one is not.
#[cfg(unix)]
#[test]
fn registration_follows_the_linked_pointer() {
    let root: PathBuf = fixture("recovery-registration");
    let (source, topic) = linked_source(root.as_path());
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    assert_eq!(
        destination_registration(common.as_path(), topic.as_path()).expect("registered"),
        Registration::Registered
    );
    let absent: PathBuf = root.join("absent");
    assert_eq!(
        destination_registration(common.as_path(), absent.as_path()).expect("absent"),
        Registration::Unregistered
    );
    let other: PathBuf = root.join("other");
    std::fs::create_dir(other.as_path()).expect("other");
    std::fs::write(other.join(".git"), b"gitdir: /nonexistent/admin\n").expect("dangling pointer");
    assert_eq!(
        destination_registration(common.as_path(), other.as_path()).expect("dangling"),
        Registration::Unregistered
    );
    let plain: PathBuf = root.join("plain");
    std::fs::create_dir(plain.as_path()).expect("plain");
    std::fs::write(plain.join(".git"), b"not a pointer\n").expect("plain pointer");
    assert_eq!(
        destination_registration(common.as_path(), plain.as_path()).expect("plain"),
        Registration::Unregistered
    );
    remove(root.as_path());
}

/// A journal whose destination is no longer registered is discarded with the notice, and its stage goes too.
#[cfg(unix)]
#[test]
fn unregistered_destination_is_discarded_with_notice() {
    let root: PathBuf = fixture("recovery-unregistered");
    let (source, topic) = linked_source(root.as_path());
    let pending: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    let stage: PathBuf = PathBuf::from(pending.journal.stage_container.as_str());
    git(
        source.as_path(),
        &[
            "worktree",
            "remove",
            "--force",
            topic.to_str().expect("utf8"),
        ],
    );
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let report: RecoveryReport =
        recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(report.recovered, 0);
    assert_eq!(
        report.notices,
        vec![format!(
            "cli-git: discarded an interrupted ignored-state copy for {}, which is no longer a registered worktree.",
            quote(topic.to_string_lossy().as_ref())
        )]
    );
    assert!(!stage.exists());
    assert!(
        read_pending_journals(common.as_path())
            .expect("pending")
            .is_empty()
    );
    remove(root.as_path());
}

/// A journal whose stage is gone is discarded with the incomplete-ignored-files notice.
#[cfg(unix)]
#[test]
fn missing_stage_is_discarded_with_notice() {
    let root: PathBuf = fixture("recovery-missing-stage");
    let (source, topic) = linked_source(root.as_path());
    let pending: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    std::fs::remove_dir_all(pending.journal.stage_container.as_str()).expect("stage removed");
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let report: RecoveryReport =
        recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(
        report.notices,
        vec![format!(
            "cli-git: discarded an interrupted ignored-state copy into {} because its private stage is missing; ignored files there may be incomplete.",
            quote(topic.to_string_lossy().as_ref())
        )]
    );
    assert!(
        read_pending_journals(common.as_path())
            .expect("pending")
            .is_empty()
    );
    remove(root.as_path());
}

/// A journal left in the installing phase with an intact stage is resumed and completed.
#[cfg(unix)]
#[test]
fn interrupted_installation_is_resumed() {
    let root: PathBuf = fixture("recovery-resume");
    let (source, topic) = linked_source(root.as_path());
    let pending: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    let installing: Journal = Journal {
        phase: Phase::Installing,
        ..pending.journal.clone()
    };
    write_journal(pending.path.as_path(), &installing).expect("installing phase");
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let report: RecoveryReport =
        recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(report.recovered, 1);
    assert!(report.notices.is_empty(), "{:?}", report.notices);
    assert_eq!(
        std::fs::read(topic.join("cache/data")).expect("resumed copy"),
        b"payload"
    );
    assert!(
        read_pending_journals(common.as_path())
            .expect("pending")
            .is_empty()
    );
    remove(root.as_path());
}

/// A copy from a main checkout that was killed after staging is resumed from its stage: the dependencies, the pnpm-style
/// links and the build output arrive, and the caches the rule leaves out never do.
#[cfg(unix)]
#[test]
fn an_interrupted_main_checkout_copy_is_resumed_from_its_stage() {
    let root: PathBuf = fixture("recovery-resume-main");
    let (source, topic) = linked_source(root.as_path());
    std::fs::write(source.join(".gitignore"), b"cache/\nnode_modules/\ntarget/\n.pnpm-store/\n").expect("gitignore");
    for (path, bytes) in [
        ("node_modules/.pnpm/dep@1/node_modules/dep/index.js", b"module".as_slice()),
        ("node_modules/.cache/jiti/x", b"cache"),
        ("target/debug/deps/libx.rlib", b"rlib"),
        ("target/debug/incremental/x", b"incremental"),
        (".pnpm-store/v11/ab", b"store"),
    ] {
        std::fs::create_dir_all(source.join(path).parent().expect("parent")).expect("directories");
        std::fs::write(source.join(path), bytes).expect("file");
    }
    std::os::unix::fs::symlink(".pnpm/dep@1/node_modules/dep", source.join("node_modules/dep")).expect("link");
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let snapshot: StagedSnapshot = stage_ignored_snapshot(
        &git_context(),
        source.as_path(),
        new_stage_container(topic.as_path()).expect("container").as_path(),
        std::slice::from_ref(&topic),
        &CopySelection::MainCheckout,
    )
    .expect("staged");
    let pending: PendingJournal = create_journal_for(common.as_path(), topic.as_path(), &snapshot, &dead_copy_owner()).expect("journal");
    write_journal(pending.path.as_path(), &Journal { phase: Phase::Installing, ..pending.journal.clone() }).expect("installing phase");
    let report: RecoveryReport = recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(report.recovered, 1);
    assert!(report.notices.is_empty(), "{:?}", report.notices);
    assert_eq!(std::fs::read(topic.join("node_modules/.pnpm/dep@1/node_modules/dep/index.js")).expect("dependency"), b"module");
    assert_eq!(
        std::fs::read_link(topic.join("node_modules/dep")).expect("link"),
        PathBuf::from(".pnpm/dep@1/node_modules/dep")
    );
    assert_eq!(std::fs::read(topic.join("target/debug/deps/libx.rlib")).expect("build"), b"rlib");
    assert!(topic.join("cache/data").exists(), "the earlier ignored directory arrives too");
    assert!(!topic.join("node_modules/.cache").exists());
    assert!(!topic.join("target/debug/incremental").exists());
    assert!(!topic.join(".pnpm-store").exists());
    assert!(read_pending_journals(common.as_path()).expect("pending").is_empty());
    remove(root.as_path());
}

/// A journal already marked complete only has its cleanup finished, and counts as recovered.
#[cfg(unix)]
#[test]
fn completed_journal_only_cleans_up() {
    let root: PathBuf = fixture("recovery-complete");
    let (source, topic) = linked_source(root.as_path());
    let pending: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    write_journal(
        pending.path.as_path(),
        &Journal {
            phase: Phase::Complete,
            ..pending.journal.clone()
        },
    )
    .expect("complete phase");
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let report: RecoveryReport =
        recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(report.recovered, 1);
    assert!(!topic.join("cache").exists());
    assert!(
        read_pending_journals(common.as_path())
            .expect("pending")
            .is_empty()
    );
    remove(root.as_path());
}

/// The pending check does nothing, and creates nothing, when no journal is pending; it leaves a live owner's journal whole
/// and recovers a dead owner's.
#[cfg(unix)]
#[test]
fn pending_check_leaves_a_live_journal_and_recovers_a_dead_one() {
    let root: PathBuf = fixture("recovery-pending-check");
    let (source, topic) = linked_source(root.as_path());
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    recover_pending_worktree_copies(common.as_path(), &mut Vec::new()).expect("nothing pending");
    assert!(!journal_root(common.as_path()).exists(), "the check creates no journal root");
    let snapshot: StagedSnapshot =
        stage_ignored_snapshot(&git_context(), source.as_path(), new_stage_container(topic.as_path()).expect("container").as_path(), &[], &CopySelection::Ignored).expect("staged");
    let live: PendingJournal = create_journal(common.as_path(), topic.as_path(), &snapshot).expect("journal of this process");
    let mut notices: Vec<u8> = Vec::new();
    recover_pending_worktree_copies(common.as_path(), &mut notices).expect("a live owner's journal is skipped");
    assert!(live.path.exists(), "a live owner keeps the journal for itself");
    assert!(notices.is_empty(), "{}", String::from_utf8_lossy(notices.as_slice()));
    assert!(Path::new(live.journal.stage_container.as_str()).exists(), "its stage stays");
    let dead: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    recover_pending_worktree_copies(common.as_path(), &mut notices).expect("a dead owner's journal is recovered");
    assert!(!dead.path.exists());
    assert!(live.path.exists(), "the live journal is still whole after the dead one went");
    remove(root.as_path());
}

/// Taking over a dead owner's journal is one rename: the first command gets it, and a second command that still holds the
/// old name gets nothing, so a journal is never installed twice.
#[cfg(unix)]
#[test]
fn only_one_command_takes_over_a_dead_journal() {
    let root: PathBuf = fixture("recovery-single-winner");
    let (source, topic) = linked_source(root.as_path());
    let dead: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    let first = dead_copy_owner();
    let second = dead_copy_owner();
    let won: PendingJournal = adopt_journal(&dead, &first).expect("rename works").expect("the first command wins");
    assert_eq!(won.owner_token(), Some(first.token()));
    assert!(won.path.exists());
    assert!(!dead.path.exists());
    assert!(adopt_journal(&dead, &second).expect("rename works").is_none(), "the old name is gone");
    remove(root.as_path());
}

/// A stage left by a copy that died before its journal existed is removed by recovery, with a notice and no count.
#[cfg(unix)]
#[test]
fn recovery_removes_a_stage_no_journal_names() {
    let root: PathBuf = fixture("recovery-abandoned-stage");
    let (source, topic) = linked_source(root.as_path());
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let claim = claim_stage_for(common.as_path(), topic.as_path(), &dead_copy_owner()).expect("claim");
    std::fs::create_dir(claim.container()).expect("stage");
    std::fs::set_permissions(claim.container(), std::fs::Permissions::from_mode(0o700)).expect("private");
    std::fs::write(claim.container().join("half"), b"copied so far").expect("partial copy");
    let report = recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(report.recovered, 0);
    assert_eq!(report.notices.len(), 1);
    assert!(report.notices[0].contains("removed the stage"), "{:?}", report.notices);
    assert!(!claim.container().exists());
    assert!(!stage_claims_exist(common.as_path()).expect("claims"));
    remove(root.as_path());
}

/// A forwarded command that creates no worktree reaps the stage of a dead owner's claim, and leaves alone the stage of a claim
/// whose owner still runs.
#[cfg(unix)]
#[test]
fn the_pending_check_reaps_abandoned_stages_only_without_a_live_owner() {
    let root: PathBuf = fixture("recovery-pending-claim");
    let (source, topic) = linked_source(root.as_path());
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let live = claim_stage(common.as_path(), topic.as_path()).expect("claim of this process");
    let dead = claim_stage_for(common.as_path(), topic.as_path(), &dead_copy_owner()).expect("claim of a dead process");
    for claim in [&live, &dead] {
        std::fs::create_dir(claim.container()).expect("stage");
        std::fs::set_permissions(claim.container(), std::fs::Permissions::from_mode(0o700)).expect("private");
    }
    let mut notices: Vec<u8> = Vec::new();
    recover_pending_worktree_copies(common.as_path(), &mut notices).expect("reaped");
    assert!(live.container().exists(), "a live copy may still be staging");
    assert!(!dead.container().exists(), "a dead owner's stage is reaped");
    assert!(stage_claims_exist(common.as_path()).expect("claims"), "the live claim stays");
    assert!(String::from_utf8_lossy(notices.as_slice()).contains("removed the stage"));
    remove(root.as_path());
}

/// The summary line counts transactions with the singular or plural noun, after the notices.
#[test]
fn report_writes_notices_then_summary() {
    let mut out: Vec<u8> = Vec::new();
    report_recovered(
        &RecoveryReport {
            recovered: 1,
            notices: vec![String::from("cli-git: notice.")],
        },
        &mut out,
    )
    .expect("written");
    assert_eq!(
        String::from_utf8(out).expect("utf8"),
        "cli-git: notice.\ncli-git: recovered ignored-state copies for 1 worktree transaction.\n"
    );
    let mut plural: Vec<u8> = Vec::new();
    report_recovered(
        &RecoveryReport {
            recovered: 2,
            notices: Vec::new(),
        },
        &mut plural,
    )
    .expect("written");
    assert_eq!(
        String::from_utf8(plural).expect("utf8"),
        "cli-git: recovered ignored-state copies for 2 worktree transactions.\n"
    );
}

/// The bytes the incumbent's own `writeJournal` wrote for a phase-installing journal, with the base directory as `@BASE@`.
/// Generated by running `createWorktreeCopyJournal` and `writeJournal` from `src/worktree-copy/journal.ts` against a scratch base directory.
const INCUMBENT_JOURNAL: &str = "{\"createdEntries\":[{\"device\":\"7\",\"inode\":\"42\",\"relativePath\":\"cache\",\"selected\":true}],\"intendedEntries\":[\"cache\"],\"destinationRoot\":\"@BASE@/topic\",\"phase\":\"installing\",\"selectedRoots\":[\"cache\"],\"sourceRoot\":\"@BASE@/source\",\"stageContainer\":\"@BASE@/.cli-git-worktree-copy-abc\",\"stageRoot\":\"@BASE@/.cli-git-worktree-copy-abc/payload\",\"version\":1}\n";

/// A journal the incumbent wrote is read by the native wrapper with the same fields, and recovered: its destination is not a worktree, so it is discarded with the incumbent's notice and its stage goes too.
#[cfg(unix)]
#[test]
fn incumbent_written_journal_is_recovered_natively() {
    let root: PathBuf = fixture("recovery-incumbent-journal");
    let common: PathBuf = root.join("common");
    std::fs::create_dir(common.as_path()).expect("common");
    let journal_root: PathBuf = ensure_journal_root(common.as_path()).expect("root");
    let base: String = root.to_string_lossy().into_owned();
    let stage: PathBuf = root.join(".cli-git-worktree-copy-abc");
    {
        use std::os::unix::fs::DirBuilderExt;
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(stage.join("payload"))
            .expect("private stage");
    }
    let text: String = INCUMBENT_JOURNAL.replace("@BASE@", base.as_str());
    let path: PathBuf = journal_root.join("6ff4c81f-f579-4616-b5d7-4c0694f77b6c.json");
    crate::private_storage::write_private_file(path.as_path(), text.as_bytes())
        .expect("incumbent journal");
    let pending: Vec<PendingJournal> = read_pending_journals(common.as_path()).expect("read");
    assert_eq!(pending.len(), 1);
    assert_eq!(pending[0].journal.phase, Phase::Installing);
    assert_eq!(
        pending[0].journal.created_entries,
        vec![InstalledPath {
            device: 7,
            inode: 42,
            relative_path: String::from("cache"),
            selected: true,
        }]
    );
    let report: RecoveryReport =
        recover_worktree_copy_transactions(common.as_path()).expect("recovered");
    assert_eq!(
        report.notices,
        vec![format!(
            "cli-git: discarded an interrupted ignored-state copy for {}, which is no longer a registered worktree.",
            quote(format!("{base}/topic").as_str())
        )]
    );
    assert!(!stage.exists());
    assert!(
        read_pending_journals(common.as_path())
            .expect("none left")
            .is_empty()
    );
    remove(root.as_path());
}

/// A destination under something that is not a directory is unregistered,
///  while a destination whose pointer cannot be read for any other reason is a fault to report.
#[cfg(unix)]
#[test]
fn registration_tells_a_missing_destination_from_an_unreadable_one() {
    let root: PathBuf = std::fs::canonicalize(fixture("recovery-registration-faults")).expect("canonical");
    let (source, _topic) = linked_source(root.as_path());
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let file: PathBuf = root.join("a-file");
    std::fs::write(file.as_path(), b"not a directory").expect("file");
    assert_eq!(
        destination_registration(common.as_path(), file.join("below").as_path()).expect("under a file"),
        Registration::Unregistered
    );
    let unreadable: PathBuf = root.join("unreadable");
    std::fs::create_dir_all(unreadable.join(".git")).expect("a directory where the pointer file belongs");
    let failure: WorktreeCopyError =
        destination_registration(common.as_path(), unreadable.as_path()).expect_err("a directory is not a pointer");
    assert!(failure.0.contains("could not read worktree registration"), "{}", failure.0);
    remove(root.as_path());
}

/// A stage that cannot be examined for any reason other than being absent is a fault, not a missing stage.
#[cfg(unix)]
#[test]
fn a_stage_that_cannot_be_examined_is_a_fault_and_not_a_missing_stage() {
    let root: PathBuf = fixture("recovery-stage-blocked");
    let (source, topic) = linked_source(root.as_path());
    let mut pending: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    let blocker: PathBuf = root.join("blocker");
    std::fs::write(blocker.as_path(), b"a file").expect("blocker");
    pending.journal.stage_container = blocker.join("stage").to_string_lossy().into_owned();
    let failure: WorktreeCopyError = validate_stage(&pending).expect_err("the stage cannot be examined");
    assert!(
        failure.0.contains("could not validate worktree-copy recovery state"),
        "{}",
        failure.0
    );
    remove(root.as_path());
}

/// Commands that race for one dead journal at the same instant produce exactly one winner, and the winner's journal is the
/// only one left under any name.
#[cfg(unix)]
#[test]
fn racing_commands_take_a_dead_journal_exactly_once() {
    const RACERS: usize = 4;
    let root: PathBuf = fixture("recovery-race");
    let (source, topic) = linked_source(root.as_path());
    let dead: PendingJournal = staged_journal(source.as_path(), topic.as_path());
    let owners: Vec<_> = (0..RACERS).map(|_racer| { return dead_copy_owner(); }).collect();
    let start: std::sync::Barrier = std::sync::Barrier::new(RACERS);
    let wins: usize = std::thread::scope(|scope| {
        let handles: Vec<_> = owners
            .iter()
            .map(|owner| {
                return scope.spawn(|| {
                    start.wait();
                    return adopt_journal(&dead, owner).expect("rename works").is_some();
                });
            })
            .collect();
        return handles.into_iter().map(|handle| { return handle.join().expect("racer ends"); }).filter(|won| { return *won; }).count();
    });
    assert_eq!(wins, 1, "exactly one command takes the journal");
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    assert_eq!(read_pending_journals(common.as_path()).expect("pending").len(), 1, "one journal remains, under the winner's name");
    remove(root.as_path());
}

/// A journal whose owner is in another PID namespace and whose file is older than the patience is neither alive nor dead (owner,
/// 2026-11-04, "Refuse and name it (Recommended)"): recovery stops with an error that names the journal, the owner, its namespace and
/// the `rm`, and nothing is taken over, finished or removed: the journal and its stage stay.
#[cfg(unix)]
#[test]
fn a_journal_of_another_namespace_older_than_the_patience_stops_recovery_and_changes_nothing() {
    let root: PathBuf = fixture("recovery-foreign-expired");
    let (source, topic) = linked_source(root.as_path());
    let common: PathBuf = std::fs::canonicalize(source.join(".git")).expect("common");
    let snapshot: StagedSnapshot =
        stage_ignored_snapshot(&git_context(), source.as_path(), new_stage_container(topic.as_path()).expect("container").as_path(), &[], &CopySelection::Ignored).expect("staged");
    let foreign = crate::worktree_copy_owner::CopyOwner { pid: 31337, birth_identity: String::from("linux:1"), pid_namespace: Some(String::from("pid:[1]")) };
    let pending: PendingJournal = create_journal_for(common.as_path(), topic.as_path(), &snapshot, &foreign).expect("journal");
    std::fs::File::options().write(true).open(pending.path.as_path()).expect("open").set_modified(std::time::SystemTime::now() - crate::pid_namespace::FOREIGN_OWNER_PATIENCE - std::time::Duration::from_secs(300)).expect("age");
    let stage: PathBuf = PathBuf::from(pending.journal.stage_container.as_str());
    let refused = recover_worktree_copy_transactions(common.as_path()).expect_err("an expired foreign journal stops recovery");
    assert!(refused.0.contains(pending.path.to_string_lossy().as_ref()) && refused.0.contains("31337") && refused.0.contains("pid:[1]") && refused.0.contains("rm -- "), "{}", refused.0);
    assert!(pending.path.exists() && stage.exists(), "the journal and its stage are untouched");
    assert_eq!(read_pending_journals(common.as_path()).expect("pending").len(), 1);
    remove(root.as_path());
}