slipcase-open 0.1.8

Open the payload of a Slipcase container in its own application, and write edits back into the container
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
//! Where a session lives on disk, and what it remembers.
//
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)
//
//! Concept 6.4. **Not the system temporary directory**, which is the obvious
//! place and the wrong one: a reboot, a `tmpfiles` cleaner or Storage Sense may
//! delete anything there, and doing so would destroy an edit the user has made
//! and the tool has not yet written back — silently, in the window concept 6.3
//! exists to survive.
//!
//! So a session is a directory under the application's own per-user state
//! directory, and recovery is a scan of that one tree rather than a record
//! pointing somewhere that may no longer be there.
//!
//! ## The payload sits one level down
//!
//! A session directory holds `session.toml` and a `payload/` directory, and the
//! payload goes inside the latter under its own name. Two reasons, and the
//! first is a collision: SPEC 2.3 permits any plain filename, `session.toml`
//! included, so a payload beside the record could overwrite it. The second is
//! that concept 6.1 reads *anything else in the directory* as the target
//! application's doing, and that inference is only sound if the tool put
//! exactly one file there.

use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

/// The file inside a session directory that carries [`Record`].
const RECORD: &str = "session.toml";

/// The directory inside a session directory that carries the payload, and
/// nothing this tool put there.
const PAYLOAD_DIR: &str = "payload";

/// How many names [`create`] will try before giving up. A thousand sessions
/// opened inside one second is not a thing that happens, and a directory that
/// somehow defeats the counter should say so rather than spin.
const ATTEMPTS: u32 = 1024;

/// What a session remembers across a crash.
///
/// Deliberately small. Concept 6.3 removed the *payload* digest this used to
/// carry: the container records a CRC-32 for its payload already, so recovery
/// compares against the container rather than against a second copy of the fact
/// that can drift from it — and drift is likeliest at the moment this file is
/// consulted.
///
/// [`Record::agreed`] is not that digest coming back, and the difference is
/// worth being exact about. The removed one answered *has the payload changed*,
/// which the container can answer better. This one answers *which side changed*,
/// which nothing can answer without a record, because both sides are only
/// visible now and the question is about then. It is a note of a past moment
/// rather than a cached copy of a present fact, so there is nothing for it to
/// drift from: if it is stale, the answer it gives — that the container is not
/// where we left it — is the true one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Record {
    /// Where the container was when the session opened, resolved. It may have
    /// moved or gone since, which concept 6.4 requires recovery to survive
    /// rather than fail at the rename.
    pub container: PathBuf,
    /// The payload's name inside the container, which is also its name inside
    /// `payload/` and therefore what decides which application opens it.
    pub payload: String,
    /// When the session opened, in seconds since the Unix epoch.
    ///
    /// A number rather than a formatted timestamp, because nothing in the tool
    /// needs to render it: concept 6.3 shows a person the payload's own
    /// modification time, which comes from the filesystem. Storing it this way
    /// keeps a date-formatting dependency out of a crate that would otherwise
    /// have no use for one.
    pub started: u64,
    /// How many write-backs this session has performed, which concept 6.2 shows
    /// beside the session.
    pub write_backs: u64,
    /// The container's payload CRC-32 at the last moment this session and the
    /// container were known to agree: the extraction, or the most recent
    /// write-back.
    ///
    /// **What it is for is telling which side moved.** A payload that differs
    /// from its container is either an edit that never landed or a container
    /// that changed underneath a dead session, and those want opposite
    /// treatment — the first is the person's own work and goes back, the second
    /// is a conflict only they can settle. Comparing the two sides now cannot
    /// separate them, because both are only observable in the present.
    ///
    /// `None` for a session written by a build that did not record it, and for
    /// one whose container could not be read at the time. Recovery treats that
    /// as *not known to agree*, which is the cautious direction: it asks.
    pub agreed: Option<u32>,
}

/// An open or recoverable session on disk.
#[derive(Debug, Clone)]
pub struct Session {
    dir: PathBuf,
    record: Record,
}

impl Session {
    /// The session's own directory.
    #[must_use]
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// What this session remembers.
    #[must_use]
    pub fn record(&self) -> &Record {
        &self.record
    }

    /// The directory the payload sits in, and the one to watch. Concept 6.1
    /// reads anything else appearing here as the target application's work.
    #[must_use]
    pub fn payload_dir(&self) -> PathBuf {
        self.dir.join(PAYLOAD_DIR)
    }

    /// The payload itself.
    #[must_use]
    pub fn payload_path(&self) -> PathBuf {
        self.payload_dir().join(&self.record.payload)
    }

    /// Count a write-back, and write that down before returning.
    ///
    /// Persisted rather than held, because the number is only worth anything to
    /// a session that crashed, and a count kept in memory is a count lost by
    /// the event it exists to describe.
    ///
    /// # Errors
    ///
    /// Where the record cannot be rewritten.
    pub fn note_write_back(&mut self) -> io::Result<()> {
        self.record.write_backs += 1;
        write_record(&self.dir, &self.record)
    }

    /// Write down that the container's payload is this, and that it is what
    /// this session's payload came from or was last put into.
    ///
    /// Called at the two moments the two sides are made to agree: the
    /// extraction, and the commit of a write-back. Nowhere else — a value
    /// recorded at any other moment would be recording an agreement that was
    /// never established, which is the one way [`Record::agreed`] could tell a
    /// lie rather than simply not know.
    ///
    /// # Errors
    ///
    /// Where the record cannot be rewritten.
    pub fn note_agreement(&mut self, crc: u32) -> io::Result<()> {
        self.record.agreed = Some(crc);
        write_record(&self.dir, &self.record)
    }

    /// Remove the session and everything in it.
    ///
    /// # Errors
    ///
    /// Where the directory cannot be removed.
    pub fn remove(self) -> io::Result<()> {
        fs::remove_dir_all(&self.dir)
    }
}

// **There was a retry here, and it was removed because what it waited for does
// not pass.** `823a972` made `remove` keep trying for three hundred
// milliseconds, on the strength of two observations: a session directory that
// would not go, and the same directory going without complaint a minute later.
// The second was read as the condition clearing on its own.
//
// It is not. The removals that failed were the packaged product's and the ones
// that succeeded were another process's, and that difference is the whole
// defect — see `platform_base` below, where the measurement is. A packaged
// process asking for `%LOCALAPPDATA%` is given a redirected view it is not told
// about, and a directory belonging to the layer underneath that view can never
// be removed through it, however long anybody waits. Fifteen of them survived
// twelve seconds of retrying.
//
// So the retry addressed nothing, and its doc comment asserted a cause that is
// now measured false. `CLAUDE.md` says an unproven claim is worse than no
// claim, because the next reader cannot tell it from a proven one; a disproven
// one left in place is worse again. If a removal here is ever seen to fail
// transiently for a reason somebody has measured, a retry comes back with that
// measurement attached.

/// The per-user state directory this build keeps sessions under.
///
/// `$XDG_STATE_HOME` on Linux, which is defined for state that must survive a
/// restart without being configuration or data, and never `XDG_RUNTIME_DIR`,
/// which is cleared at logout. `~/Library/Application Support` on macOS rather
/// than `Caches`, which the system may purge at will. `%LOCALAPPDATA%` on
/// Windows and deliberately not the roaming profile, since an extracted payload
/// cannot follow a user between machines.
///
/// # Errors
///
/// Where the platform names no home for this, which is a machine too unusual to
/// guess about rather than a condition to work around.
pub fn default_root() -> io::Result<PathBuf> {
    let base = platform_base().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            "no per-user state directory: set XDG_STATE_HOME, HOME, or LOCALAPPDATA",
        )
    })?;
    Ok(base.join("slipcase-open").join("sessions"))
}

#[cfg(target_os = "linux")]
fn platform_base() -> Option<PathBuf> {
    if let Some(x) = std::env::var_os("XDG_STATE_HOME").filter(|v| !v.is_empty()) {
        return Some(PathBuf::from(x));
    }
    // The fallback the XDG base directory specification names, rather than one
    // of this project's choosing.
    Some(PathBuf::from(std::env::var_os("HOME")?).join(".local/state"))
}

#[cfg(target_os = "macos")]
fn platform_base() -> Option<PathBuf> {
    Some(PathBuf::from(std::env::var_os("HOME")?).join("Library/Application Support"))
}

/// `%LOCALAPPDATA%` where this process is an ordinary program, and the
/// package's own store where it is a packaged one — asked of Windows rather
/// than assumed.
///
/// **A packaged process that asks for `%LOCALAPPDATA%` does not get it, and is
/// not told.** Measured on 2026-09-05 against the installed 0.1.4 package: with
/// both roots emptied and a container opened through the shell verb, no
/// `%LOCALAPPDATA%\slipcase-open` was created at all and the session appeared
/// under `…\Packages\<family>\LocalCache\Local\slipcase-open\sessions`. MSIX
/// redirects that variable, and the read view is *merged*, so the process also
/// sees whatever is in the real location and cannot tell the two apart.
///
/// **That merge is what produced the sessions surviving their own removal**,
/// which `PLAN.md` carried as an open defect with three explanations measured
/// and found wrong. A redirection layer can tombstone a *file* in the layer
/// beneath it and cannot remove a *directory* there, so `remove_dir_all`
/// unlinked the payload and failed on `payload/` with `ERROR_SHARING_VIOLATION`
/// — for ever, not transiently, and with no process holding anything. Measured
/// the same day: the same executable, byte for byte, with the same package
/// identity, removes the directory when it runs from a staging tree and never
/// removes it when it runs from the package's install location; fifteen such
/// directories survived twelve seconds of a packaged sweep retrying them, while
/// any other process removed each one on the first ask.
///
/// So the answer is to stop asking for a path this process will not be given.
/// `LocalCacheFolder` and not `LocalFolder`: both were measured to create and
/// remove cleanly here, and the cache is the one Windows neither roams nor
/// includes in a device backup, which is what a copy of somebody's payload
/// should be — concept 17's backup-exposure question, settled on this platform
/// by where the directory is rather than by a warning about it.
#[cfg(target_os = "windows")]
fn platform_base() -> Option<PathBuf> {
    package_store().or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from))
}

/// Where Windows says this package keeps its data, or `None` where there is no
/// package.
///
/// **On a thread of its own, and that is not caution.** Answering this enters a
/// COM apartment, and the launch path enters a single-threaded one later
/// because `ShellExecuteEx` hands work to shell extensions that require it
/// (`platform::shell`). A multi-threaded apartment entered here first would
/// make that call fail with `RPC_E_CHANGED_MODE` and leave the launcher running
/// in the wrong model — a real regression bought for a path lookup. A thread
/// that exits takes its apartment with it.
///
/// **Identity is asked about before `WinRT` is touched, because without a package
/// `ApplicationData::Current` does not fail — it crashes.** Measured while
/// writing this: the suite died with `STATUS_ACCESS_VIOLATION` the first time
/// this function ran in a test binary, which has no package. So the question
/// *is there a package* is put to a plain Win32 call that answers it with an
/// error code, and the `WinRT` call is only ever made where the answer was yes.
/// `Toast::connect` gets away with the direct attempt because
/// `CreateToastNotifier` refuses politely; this one does not, and the two are
/// not interchangeable.
#[cfg(target_os = "windows")]
fn package_store() -> Option<PathBuf> {
    if !packaged() {
        return None;
    }
    std::thread::spawn(|| {
        use windows::Storage::ApplicationData;
        apartment();
        let path = ApplicationData::Current()
            .ok()?
            .LocalCacheFolder()
            .ok()?
            .Path()
            .ok()?;
        Some(PathBuf::from(path.to_os_string()))
    })
    .join()
    .ok()
    .flatten()
}

/// Whether this process is running with package identity.
///
/// `GetCurrentPackageFamilyName` asked with no buffer: a packaged process is
/// told the buffer is too small, and an unpackaged one is told there is no
/// package. Nothing is read back, so the name itself is never needed — the
/// question here is only which of those two answers comes.
#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
fn packaged() -> bool {
    use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
    use windows_sys::Win32::Storage::Packaging::Appx::GetCurrentPackageFamilyName;

    let mut len: u32 = 0;
    // SAFETY: the documented way to ask for the required length. The length is
    // in-out and lives here; the buffer is null, which is what a zero length
    // licenses, and nothing is written through it.
    let how = unsafe { GetCurrentPackageFamilyName(&raw mut len, std::ptr::null_mut()) };
    how == ERROR_INSUFFICIENT_BUFFER
}

/// A multi-threaded apartment for the calling thread, which `WinRT` activation
/// needs and which this crate only ever enters on a thread it is about to
/// throw away.
#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
fn apartment() {
    use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
    // SAFETY: the documented entry point, with no reserved parameter, on a
    // thread this function owns. The result is ignored deliberately: `S_FALSE`
    // means somebody had already entered on this thread, and there is nobody
    // else on this one.
    let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn platform_base() -> Option<PathBuf> {
    None
}

/// Start a session under `root`, creating the tree if it is not there.
///
/// The container path is resolved before it is written down, so a container
/// reached through a symbolic link records the file rather than the link, and
/// so that what recovery reads later is a path and not a relative fragment
/// interpreted against whatever directory a later process happens to be in.
///
/// # Errors
///
/// Where the container cannot be resolved, or the tree cannot be created.
pub fn create(root: &Path, container: &Path, payload: &str) -> io::Result<Session> {
    let container = fs::canonicalize(container)?;
    let started = seconds_since_epoch();

    create_private_dir_all(root)?;

    // Named for when it started and made unique by the create itself, which is
    // atomic. No randomness: the root is the user's own and private, and a
    // counter that cannot collide is a smaller thing to get right than a source
    // of entropy would be.
    let mut made = None;
    for n in 0..ATTEMPTS {
        let candidate = root.join(format!("{started:x}-{n}"));
        match fs::create_dir(&candidate) {
            Ok(()) => {
                made = Some(candidate);
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e),
        }
    }
    let Some(dir) = made else {
        return Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            format!("{ATTEMPTS} session directories already exist for this second"),
        ));
    };
    private(&dir)?;

    let session = Session {
        record: Record {
            container,
            payload: payload.to_string(),
            started,
            write_backs: 0,
            // Not known yet. `extract` is what sets it, because that is the
            // moment the two are made to agree.
            agreed: None,
        },
        dir,
    };

    create_private_dir_all(&session.payload_dir())?;
    write_record(&session.dir, &session.record)?;
    Ok(session)
}

/// Every session under `root`, open or left behind.
///
/// A directory carrying no readable record is skipped rather than reported: it
/// is a session being created by another process right now, or the remains of
/// one that died between the two operations, and neither is something to fail a
/// recovery scan over.
///
/// # Errors
///
/// Where `root` exists and cannot be read. A `root` that is not there yet is an
/// empty list, because a machine that has never opened a container has no
/// sessions rather than a problem.
pub fn scan(root: &Path) -> io::Result<Vec<Session>> {
    let entries = match fs::read_dir(root) {
        Ok(e) => e,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };
    let mut found: Vec<Session> = entries
        .flatten()
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
        .filter_map(|e| {
            let dir = e.path();
            read_record(&dir).ok().map(|record| Session { dir, record })
        })
        .collect();
    found.sort_by(|a, b| a.dir.cmp(&b.dir));
    Ok(found)
}

/// The session under `root` with this directory name.
///
/// The name is what [`scan`] shows, so it is what a person types back.
///
/// # Errors
///
/// Where there is no such session, or its record cannot be read.
pub fn find(root: &Path, id: &str) -> io::Result<Session> {
    // Rejected rather than joined. A name carrying a separator would reach out
    // of the root, and the only names this answers to are ones `scan` printed.
    if id.is_empty() || id.contains(['/', '\\']) || id == "." || id == ".." {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("no session {id}"),
        ));
    }
    let dir = root.join(id);
    let record = read_record(&dir)?;
    Ok(Session { dir, record })
}

fn seconds_since_epoch() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// Create a directory and its parents, owner-only.
fn create_private_dir_all(at: &Path) -> io::Result<()> {
    fs::create_dir_all(at)?;
    private(at)
}

/// Narrow a directory to its owner.
///
/// Set after creation rather than through the umask, because the umask is the
/// user's and a permissive one would leave a payload readable by every account
/// on the machine. Windows needs nothing: `%LOCALAPPDATA%` is already scoped by
/// an inherited ACL, and there is no mode to set.
#[cfg(unix)]
fn private(at: &Path) -> io::Result<()> {
    use std::os::unix::fs::PermissionsExt as _;
    fs::set_permissions(at, fs::Permissions::from_mode(0o700))
}

/// Nothing to narrow, for the reason the arm above gives. `Result` because that
/// arm has one to give.
#[allow(clippy::unnecessary_wraps)]
#[cfg(not(unix))]
fn private(_at: &Path) -> io::Result<()> {
    Ok(())
}

fn write_record(dir: &Path, record: &Record) -> io::Result<()> {
    let mut doc = toml_edit::DocumentMut::new();
    // Lossy is wrong for a path and right for nothing, so a path that is not
    // Unicode is refused here rather than written down wrongly and acted on
    // later. Rare on every platform this ships to, and silently mangling a
    // container's location is worse than saying so.
    let container = record.container.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "container path is not Unicode: {}",
                record.container.display()
            ),
        )
    })?;
    doc["container"] = toml_edit::value(container);
    doc["payload"] = toml_edit::value(record.payload.as_str());
    doc["started"] = toml_edit::value(i64::try_from(record.started).unwrap_or(i64::MAX));
    doc["write_backs"] = toml_edit::value(i64::try_from(record.write_backs).unwrap_or(i64::MAX));
    if let Some(agreed) = record.agreed {
        doc["agreed"] = toml_edit::value(i64::from(agreed));
    }
    fs::write(dir.join(RECORD), doc.to_string())
}

fn read_record(dir: &Path) -> io::Result<Record> {
    let text = fs::read_to_string(dir.join(RECORD))?;
    let doc: toml_edit::DocumentMut = text
        .parse()
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{RECORD}: {e}")))?;

    let mut want = BTreeMap::new();
    for key in ["container", "payload"] {
        let v = doc.get(key).and_then(|v| v.as_str()).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("{RECORD}: no string `{key}`"),
            )
        })?;
        want.insert(key, v.to_string());
    }
    let number = |key: &str| -> u64 {
        doc.get(key)
            .and_then(toml_edit::Item::as_integer)
            .and_then(|n| u64::try_from(n).ok())
            .unwrap_or_default()
    };

    Ok(Record {
        container: PathBuf::from(&want["container"]),
        payload: want["payload"].clone(),
        started: number("started"),
        write_backs: number("write_backs"),
        // Absent where an older build wrote this, which recovery reads as not
        // known to agree rather than as agreeing.
        agreed: doc
            .get("agreed")
            .and_then(toml_edit::Item::as_integer)
            .and_then(|n| u32::try_from(n).ok()),
    })
}

#[cfg(test)]
mod tests {
    use super::{create, default_root, scan, PAYLOAD_DIR, RECORD};
    use std::fs;

    /// A container on disk to point a session at. Its contents do not matter
    /// here; what matters is that the path resolves.
    fn a_container(at: &std::path::Path) -> std::path::PathBuf {
        let p = at.join("report.pdf.slpc");
        fs::write(&p, b"not a real container").unwrap();
        p
    }

    #[test]
    fn a_session_holds_its_record_and_a_payload_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        let s = create(&root, &c, "report.pdf").unwrap();
        assert!(s.dir().join(RECORD).is_file());
        assert!(s.payload_dir().is_dir());
        assert_eq!(s.payload_dir().file_name().unwrap(), PAYLOAD_DIR);
        assert_eq!(s.payload_path(), s.payload_dir().join("report.pdf"));
    }

    #[test]
    fn the_payload_sits_below_the_record_rather_than_beside_it() {
        // SPEC 2.3 permits any plain filename, `session.toml` included, so a
        // payload beside the record could overwrite it. And concept 6.1 reads
        // anything else in the payload directory as the target application's
        // doing, which is only sound if the tool put one file there.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        let s = create(&root, &c, RECORD).unwrap();
        fs::write(s.payload_path(), b"payload").unwrap();

        assert!(s.dir().join(RECORD).is_file());
        assert!(fs::read_to_string(s.dir().join(RECORD))
            .unwrap()
            .contains("payload ="));
        assert_eq!(fs::read(s.payload_path()).unwrap(), b"payload");
    }

    #[test]
    fn the_container_path_is_resolved_before_it_is_written_down() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        // Reached through a relative fragment, which a later process in another
        // working directory could not interpret.
        let previous = std::env::current_dir().unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();
        let s = create(&root, std::path::Path::new("report.pdf.slpc"), "report.pdf");
        std::env::set_current_dir(previous).unwrap();

        let s = s.unwrap();
        assert!(s.record().container.is_absolute());
        assert_eq!(s.record().container, fs::canonicalize(&c).unwrap());
    }

    #[test]
    fn two_sessions_on_the_same_container_get_directories_of_their_own() {
        // Whether that should be allowed is concept 8's question and the
        // engine's answer. This is only that the naming does not collide.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        let a = create(&root, &c, "report.pdf").unwrap();
        let b = create(&root, &c, "report.pdf").unwrap();
        assert_ne!(a.dir(), b.dir());
    }

    #[test]
    fn a_session_survives_being_written_and_read_back() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        // A name carrying the characters that would break a hand-rolled
        // writer. SPEC 2.3 permits both.
        let mut s = create(&root, &c, "a \"quoted\" \\ name.pdf").unwrap();
        s.note_write_back().unwrap();
        s.note_write_back().unwrap();

        let found = scan(&root).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].record(), s.record());
        assert_eq!(found[0].record().write_backs, 2);
    }

    #[test]
    fn a_write_back_count_is_on_disk_before_the_call_returns() {
        // It is only worth anything to a session that crashed, so a count kept
        // in memory is a count lost by the event it describes.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        let mut s = create(&root, &c, "report.pdf").unwrap();
        s.note_write_back().unwrap();
        assert_eq!(scan(&root).unwrap()[0].record().write_backs, 1);
    }

    #[test]
    fn scanning_a_root_that_is_not_there_finds_nothing_rather_than_failing() {
        // A machine that has never opened a container has no sessions rather
        // than a problem, and recovery runs on every launch.
        let tmp = tempfile::tempdir().unwrap();
        assert!(scan(&tmp.path().join("never-used")).unwrap().is_empty());
    }

    #[test]
    fn a_directory_with_no_readable_record_is_skipped_rather_than_fatal() {
        // Another process creating a session right now, or the remains of one
        // that died between the two operations. Neither should fail a scan.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());
        let good = create(&root, &c, "report.pdf").unwrap();

        fs::create_dir(root.join("half-made")).unwrap();
        fs::write(root.join("truncated"), b"not a directory").unwrap();
        fs::create_dir(root.join("garbled")).unwrap();
        fs::write(root.join("garbled").join(RECORD), b"= not toml =").unwrap();

        let found = scan(&root).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].dir(), good.dir());
    }

    #[test]
    fn removing_a_session_takes_the_payload_with_it() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        let s = create(&root, &c, "report.pdf").unwrap();
        fs::write(s.payload_path(), b"edited").unwrap();
        let dir = s.dir().to_path_buf();
        s.remove().unwrap();

        assert!(!dir.exists());
        assert!(scan(&root).unwrap().is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn the_tree_is_owner_only_whatever_the_umask_says() {
        use std::os::unix::fs::PermissionsExt as _;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());

        let s = create(&root, &c, "report.pdf").unwrap();
        for d in [&root, &s.dir().to_path_buf(), &s.payload_dir()] {
            let mode = fs::metadata(d).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o700, "{}", d.display());
        }
    }

    #[test]
    fn the_default_root_is_under_the_platforms_state_directory() {
        // Not asserted against a literal path, which would only restate the
        // code. What matters is that it is named, that it is not the system
        // temporary directory, and that sessions are under a directory of this
        // application's own.
        let root = default_root().unwrap();
        assert!(root.ends_with("slipcase-open/sessions"));
        assert!(!root.starts_with(std::env::temp_dir()));
    }

    #[cfg(windows)]
    #[test]
    fn with_no_package_around_it_the_root_is_the_one_the_environment_names() {
        // The suite runs unpackaged, so `package_store` has nothing to answer
        // with and the fallback is what decides. This pins that: the lookup
        // added for the packaged case must not change where an ordinary build
        // keeps its sessions, which is where every existing install's are.
        //
        // What it cannot check is the packaged answer, because a test binary
        // cannot have package identity. That half is measured against an
        // installed package and written up in `platform_base`.
        assert!(super::package_store().is_none());
        let named = std::path::PathBuf::from(std::env::var_os("LOCALAPPDATA").unwrap());
        assert_eq!(
            default_root().unwrap(),
            named.join("slipcase-open").join("sessions")
        );
    }

    #[test]
    fn removing_a_session_takes_the_payload_and_the_record_with_it() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let c = a_container(tmp.path());
        let s = create(&root, &c, "report.pdf").unwrap();
        fs::write(s.payload_path(), b"something").unwrap();
        let dir = s.dir().to_path_buf();

        s.remove().unwrap();
        assert!(!dir.exists());
        assert!(scan(&root).unwrap().is_empty());
    }
}