Skip to main content

agentmux_srv_core/backend/transcript/
provider_end.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The end of a provider session (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 5.2 to 5.4): prove that the
5//! store holds what the provider's files hold, import what it does not, and only then remove the files, by session id.
6//!
7//! Nothing here decides *when* a session ends or *which* ids AgentMux started; the caller passes one session's files.
8//! The proof is [`super::provider`]'s: a file's records matched against the store's, in order. What does not match is
9//! written to the zone as it is (`import/<session>/<file>`), a provider file that is not line records (a spill file)
10//! is imported whole, and the fields a matched record has that the store's line lacks go to `output.provider`.
11//! After the import the written data is read back and compared; **a file is removed only when every record and every
12//! file of the session is matched or read back equal.** A failure removes nothing and reports counts only.
13
14use std::collections::HashSet;
15use std::io::{BufRead, BufReader, Read, Write};
16use std::path::{Path, PathBuf};
17
18use serde_json::{json, Value};
19use sha2::{Digest, Sha256};
20
21use super::provider::{record, sidecar_fields, Matcher, Record, StoreIndex};
22use super::withhold;
23use crate::backend::agent_session::OUTPUT_FILE;
24
25/// The file in a zone that keeps what the provider's matched records carry beyond the store's lines.
26pub const SIDECAR_FILE: &str = "output.provider";
27
28/// How much of a file is read or written at a time.
29const CHUNK: u64 = 4 << 20;
30
31/// A zone of the store, as the proof and the import use it.
32pub trait Zone {
33    fn size(&self, name: &str) -> Result<u64, String>;
34    fn chunk(&self, name: &str, offset: u64, len: u64) -> Result<Vec<u8>, String>;
35    /// Append, creating the file when it is not there.
36    fn append(&self, name: &str, bytes: &[u8]) -> Result<(), String>;
37    fn delete(&self, name: &str) -> Result<(), String>;
38
39    fn read_all(&self, name: &str) -> Result<Vec<u8>, String> {
40        let size = self.size(name)?;
41        let mut out = Vec::with_capacity(size as usize);
42        let mut at = 0;
43        while at < size {
44            let part = self.chunk(name, at, CHUNK.min(size - at))?;
45            if part.is_empty() {
46                return Err(format!("short read of {name}"));
47            }
48            at += part.len() as u64;
49            out.extend_from_slice(&part);
50        }
51        Ok(out)
52    }
53}
54
55/// One zone of a [`FileStore`](crate::backend::storage::filestore::FileStore).
56pub struct FsZone<'a> {
57    pub fs: &'a crate::backend::storage::filestore::FileStore,
58    pub zone: &'a str,
59}
60
61impl Zone for FsZone<'_> {
62    fn size(&self, name: &str) -> Result<u64, String> {
63        Ok(self.fs.stat(self.zone, name).map_err(|e| e.to_string())?.map_or(0, |f| f.size.max(0) as u64))
64    }
65
66    fn chunk(&self, name: &str, offset: u64, len: u64) -> Result<Vec<u8>, String> {
67        self.fs.read_bytes_db(self.zone, name, offset as i64, len as i64).map_err(|e| e.to_string())
68    }
69
70    fn append(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
71        use crate::backend::storage::error::StoreError;
72        use crate::backend::storage::filestore::FileOpts;
73        let put = || self.fs.append_data(self.zone, name, bytes);
74        match put() {
75            Err(StoreError::NotFound) => match self.fs.make_file(self.zone, name, Default::default(), FileOpts::default()) {
76                Ok(()) | Err(StoreError::AlreadyExists) => put().map_err(|e| e.to_string()),
77                Err(e) => Err(e.to_string()),
78            },
79            other => other.map_err(|e| e.to_string()),
80        }
81    }
82
83    fn delete(&self, name: &str) -> Result<(), String> {
84        match self.fs.delete_file(self.zone, name) {
85            Ok(()) | Err(crate::backend::storage::error::StoreError::NotFound) => Ok(()),
86            Err(e) => Err(e.to_string()),
87        }
88    }
89}
90
91/// The store's items for a session, read from each zone's `output` in turn (the oldest conversation first, so
92/// the order the proof matches in is the order the conversation was written in).
93pub fn index_store(zones: &[&dyn Zone], sid: &str) -> Result<StoreIndex, String> {
94    let mut index = StoreIndex::new();
95    for zone in zones {
96        index_zone(*zone, sid, &mut index)?;
97    }
98    Ok(index)
99}
100
101/// Add one zone's `output`, read a chunk at a time.
102fn index_zone(zone: &dyn Zone, sid: &str, index: &mut StoreIndex) -> Result<(), String> {
103    let size = zone.size(OUTPUT_FILE)?;
104    let mut carry: Vec<u8> = Vec::new();
105    let mut at = 0;
106    while at < size {
107        let part = zone.chunk(OUTPUT_FILE, at, CHUNK.min(size - at))?;
108        if part.is_empty() {
109            return Err("short read of output".to_string());
110        }
111        at += part.len() as u64;
112        carry.extend_from_slice(&part);
113        let mut start = 0;
114        while let Some(i) = carry[start..].iter().position(|b| *b == b'\n') {
115            index.add_line(sid, &String::from_utf8_lossy(&carry[start..start + i]));
116            start += i + 1;
117        }
118        carry.drain(..start);
119    }
120    if !carry.is_empty() {
121        index.add_line(sid, &String::from_utf8_lossy(&carry));
122    }
123    Ok(())
124}
125
126/// When anything the session holds was last written, as ms since the epoch: the newest of its session file and every
127/// file under its folder. `None` when it has no file.
128pub fn newest_modified_ms(files: &SessionFiles) -> Option<i64> {
129    let stamp = |p: &Path| -> Option<i64> {
130        let t = std::fs::metadata(p).ok()?.modified().ok()?;
131        Some(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis() as i64)
132    };
133    members(files).ok()?.iter().filter_map(|m| stamp(&m.path)).max()
134}
135
136/// What every file of the session holds right now, in order: its name inside the session, its size and its SHA-256. A
137/// copy of a session is the same session when its fingerprint is equal (the container path compares the staged copy
138/// with what the container holds before it removes anything there). A link or a special file is an error.
139pub fn fingerprint(files: &SessionFiles) -> Result<Vec<(String, u64, [u8; 32])>, String> {
140    members(files)?.into_iter().map(|m| file_digest(&m.path).map(|(size, sum)| (m.rel, size, sum))).collect()
141}
142
143/// A session id that names a file safely: letters, digits, `-` and `_`, and no longer than a path part needs.
144pub fn valid_sid(sid: &str) -> bool {
145    (8..=80).contains(&sid.len()) && sid.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
146}
147
148/// One session's files under a project folder: `<sid>.jsonl` and the `<sid>/` folder beside it.
149pub struct SessionFiles {
150    pub sid: String,
151    pub jsonl: PathBuf,
152    pub folder: PathBuf,
153}
154
155impl SessionFiles {
156    /// `None` when `sid` is not a plain id: nothing is ever named from a string with a separator in it.
157    pub fn at(project_dir: &Path, sid: &str) -> Option<Self> {
158        valid_sid(sid).then(|| Self { sid: sid.to_string(), jsonl: project_dir.join(format!("{sid}.jsonl")), folder: project_dir.join(sid) })
159    }
160}
161
162/// A regular file of a session: where it is and its name inside the session (`/`-separated).
163struct Member {
164    rel: String,
165    path: PathBuf,
166}
167
168/// Every file of the session, the session file first. A link or anything that is not a regular file or folder is an
169/// error, and so is a missing session: the caller removes nothing.
170fn members(files: &SessionFiles) -> Result<Vec<Member>, String> {
171    let mut out = Vec::new();
172    match std::fs::symlink_metadata(&files.jsonl) {
173        Ok(m) if m.is_file() => out.push(Member { rel: format!("{}.jsonl", files.sid), path: files.jsonl.clone() }),
174        Ok(_) => return Err("the session file is not a regular file".to_string()),
175        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
176        Err(e) => return Err(format!("the session file: {e}")),
177    }
178    match std::fs::symlink_metadata(&files.folder) {
179        Ok(m) if m.is_dir() => walk(&files.folder, "", &mut out)?,
180        Ok(_) => return Err("the session folder is not a folder".to_string()),
181        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
182        Err(e) => return Err(format!("the session folder: {e}")),
183    }
184    Ok(out)
185}
186
187fn walk(dir: &Path, prefix: &str, out: &mut Vec<Member>) -> Result<(), String> {
188    let mut entries: Vec<_> = std::fs::read_dir(dir).map_err(|e| e.to_string())?.collect::<Result<_, _>>().map_err(|e: std::io::Error| e.to_string())?;
189    entries.sort_by_key(|e| e.file_name());
190    for e in entries {
191        let name = e.file_name().to_string_lossy().into_owned();
192        let rel = if prefix.is_empty() { format!("session/{name}") } else { format!("{prefix}/{name}") };
193        let m = std::fs::symlink_metadata(e.path()).map_err(|e| e.to_string())?;
194        if m.is_dir() {
195            walk(&e.path(), &rel, out)?;
196        } else if m.is_file() {
197            out.push(Member { rel, path: e.path() });
198        } else {
199            return Err("the session folder holds a link or a special file".to_string());
200        }
201    }
202    Ok(())
203}
204
205/// What the proof found in one file.
206struct FileProof {
207    rel: String,
208    path: PathBuf,
209    records: usize,
210    matched: usize,
211    /// The lines to import, verbatim (a line-record file only).
212    unmatched: Vec<String>,
213    /// For matched records: (line number, fields).
214    sidecar: Vec<(usize, Value)>,
215    /// The file is not UTF-8 line records: it is imported whole.
216    whole: bool,
217    /// What an import of the whole file writes, as size and digest (masked as the store masks).
218    want: Option<Sum>,
219}
220
221type Sum = (u64, [u8; 32]);
222
223fn prove_lines(m: &Member, index: &StoreIndex) -> Result<FileProof, String> {
224    let mut proof = FileProof { rel: m.rel.clone(), path: m.path.clone(), records: 0, matched: 0, unmatched: Vec::new(), sidecar: Vec::new(), whole: false, want: None };
225    let mut reader = BufReader::new(std::fs::File::open(&m.path).map_err(|e| e.to_string())?);
226    let mut matcher = Matcher::new(index);
227    let mut buf = Vec::new();
228    let mut n = 0;
229    loop {
230        buf.clear();
231        if reader.read_until(b'\n', &mut buf).map_err(|e| e.to_string())? == 0 {
232            break;
233        }
234        n += 1;
235        while matches!(buf.last(), Some(b'\n' | b'\r')) {
236            buf.pop();
237        }
238        if buf.is_empty() {
239            continue;
240        }
241        let Ok(text) = std::str::from_utf8(&buf) else {
242            return whole_proof(m);
243        };
244        proof.records += 1;
245        let r: Record = record(n, text);
246        if matcher.matches(&r) {
247            proof.matched += 1;
248            if let Some(f) = sidecar_fields(&r) {
249                proof.sidecar.push((n, Value::Object(f)));
250            }
251        } else {
252            proof.unmatched.push(r.line);
253        }
254    }
255    Ok(proof)
256}
257
258fn is_lines_file(m: &Member) -> bool {
259    m.path.extension().is_some_and(|e| e == "jsonl")
260}
261
262fn import_name(sid: &str, rel: &str) -> String {
263    format!("import/{sid}/{rel}")
264}
265
266fn lines_set(bytes: &[u8]) -> HashSet<String> {
267    String::from_utf8_lossy(bytes).split('\n').filter(|l| !l.is_empty()).map(str::to_string).collect()
268}
269
270/// A file imported whole is read into memory, so a file past this is not imported (and its session not removed).
271const MAX_WHOLE_BYTES: u64 = 256 << 20;
272
273/// What an import of a whole file writes: the bytes with a value srv holds secret replaced by its mark. A file that is
274/// not UTF-8 cannot be masked, so one that holds a secret in any spelling is refused rather than written in clear.
275fn imported_bytes(path: &Path) -> Result<Vec<u8>, String> {
276    if std::fs::metadata(path).map_err(|e| e.to_string())?.len() > MAX_WHOLE_BYTES {
277        return Err("a file of the session is too large to import whole".to_string());
278    }
279    let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
280    match String::from_utf8(bytes) {
281        Ok(text) => Ok(withhold::text(&text).into_owned().into_bytes()),
282        Err(e) => {
283            let bytes = e.into_bytes();
284            if withhold::holds(&String::from_utf8_lossy(&bytes)) {
285                return Err("a file that is not text holds a value that is withheld".to_string());
286            }
287            Ok(bytes)
288        }
289    }
290}
291
292fn bytes_digest(bytes: &[u8]) -> Sum {
293    (bytes.len() as u64, Sha256::digest(bytes).into())
294}
295
296fn whole_proof(m: &Member) -> Result<FileProof, String> {
297    let want = bytes_digest(&imported_bytes(&m.path)?);
298    Ok(FileProof { rel: m.rel.clone(), path: m.path.clone(), records: 0, matched: 0, unmatched: Vec::new(), sidecar: Vec::new(), whole: true, want: Some(want) })
299}
300
301fn file_digest(path: &Path) -> Result<Sum, String> {
302    let mut f = std::fs::File::open(path).map_err(|e| e.to_string())?;
303    let mut h = Sha256::new();
304    let mut buf = vec![0u8; 1 << 20];
305    let mut total = 0u64;
306    loop {
307        let n = f.read(&mut buf).map_err(|e| e.to_string())?;
308        if n == 0 {
309            return Ok((total, h.finalize().into()));
310        }
311        total += n as u64;
312        h.update(&buf[..n]);
313    }
314}
315
316fn zone_digest(zone: &dyn Zone, name: &str) -> Result<Sum, String> {
317    let size = zone.size(name)?;
318    let mut h = Sha256::new();
319    let mut at = 0;
320    while at < size {
321        let part = zone.chunk(name, at, CHUNK.min(size - at))?;
322        if part.is_empty() {
323            return Err(format!("short read of {name}"));
324        }
325        at += part.len() as u64;
326        h.update(&part);
327    }
328    Ok((size, h.finalize().into()))
329}
330
331/// Write a file's bytes whole under `name`, replacing what is there.
332fn import_whole(zone: &dyn Zone, name: &str, path: &Path) -> Result<(), String> {
333    let bytes = imported_bytes(path)?;
334    zone.delete(name)?;
335    for part in bytes.chunks(CHUNK as usize) {
336        zone.append(name, part)?;
337    }
338    Ok(())
339}
340
341/// Append the lines of `lines` that the zone's file does not already hold.
342fn import_lines(zone: &dyn Zone, name: &str, lines: &[String]) -> Result<(), String> {
343    let held = lines_set(&zone.read_all(name)?);
344    let mut out = String::new();
345    for l in lines.iter().filter(|l| !held.contains(*l)) {
346        out.push_str(l);
347        out.push('\n');
348    }
349    zone.append(name, out.as_bytes())
350}
351
352fn sidecar_line(sid: &str, rel: &str, n: usize, fields: &Value) -> String {
353    json!({ "s": sid, "f": rel, "n": n, "fields": fields }).to_string()
354}
355
356/// While secret matching is closed every line reads as the mark: nothing may be proved or imported then.
357fn require_open_matching(mode: &str) -> Result<(), String> {
358    if mode == "closed" {
359        return Err("secret matching is closed: no provider file is read".to_string());
360    }
361    Ok(())
362}
363
364/// What the caller holds across the removal (an agent's lease): the removal asks before each file whether it is
365/// still held, and stops when it is not.
366pub trait Hold {
367    fn still_held(&self) -> Result<(), String>;
368}
369
370impl Hold for () {
371    fn still_held(&self) -> Result<(), String> {
372        Ok(())
373    }
374}
375
376/// What the end of a session did, in counts.
377#[derive(Debug, Default, PartialEq, Eq)]
378pub struct Outcome {
379    pub files: usize,
380    pub records: usize,
381    pub matched: usize,
382    pub imported_records: usize,
383    pub imported_files: usize,
384    pub removed_files: usize,
385}
386
387/// Prove, import, verify and remove one session's files. `before_remove` runs after the verify and before any file is
388/// touched: an `Err` stops with nothing removed, and what it returns is kept until the removal is done and asked before
389/// each file whether it is still held. `erase` is called for each file after it is overwritten and
390/// before it is unlinked (a test's hook; pass a no-op otherwise). Nothing is removed unless every record and file is
391/// matched or read back equal; an `Err` has removed nothing.
392pub fn end_session(
393    files: &SessionFiles,
394    read: &[&dyn Zone],
395    zone: &dyn Zone,
396    before_remove: &mut dyn FnMut() -> Result<Box<dyn Hold>, String>,
397    erase: &mut dyn FnMut(&Path, u64),
398) -> Result<Outcome, String> {
399    require_open_matching(&withhold::health().mode)?;
400    let members = members(files)?;
401    let index = index_store(read, &files.sid)?;
402    // What each file is before the proof reads it: removal checks it is still that.
403    let mut raw = Vec::new();
404    for m in &members {
405        raw.push((m.path.clone(), file_digest(&m.path)?));
406    }
407    let mut proofs = Vec::new();
408    for m in &members {
409        proofs.push(if is_lines_file(m) { prove_lines(m, &index)? } else { whole_proof(m)? });
410    }
411    import(files, zone, &proofs)?;
412    verify(files, zone, &proofs)?;
413    // The caller's last word, held until the files are gone: it may refuse (nothing is removed) or return what it
414    // holds across the removal.
415    let held = before_remove()?;
416    let removed = remove_proved(files, &raw, &*held, erase)?;
417    let mut out = Outcome { files: members.len(), removed_files: removed, ..Default::default() };
418    for p in &proofs {
419        out.records += p.records;
420        out.matched += p.matched;
421        out.imported_records += p.unmatched.len();
422        out.imported_files += usize::from(p.whole);
423    }
424    Ok(out)
425}
426
427/// What the proof alone found in one session. Nothing is written, imported or removed.
428#[derive(Debug, Default, PartialEq, Eq)]
429pub struct ProofCounts {
430    pub files: usize,
431    pub bytes: u64,
432    /// Line records read, of which `matched` are in the store.
433    pub records: usize,
434    pub matched: usize,
435    /// Records the store lacks: an end of the session would import them first.
436    pub unmatched: usize,
437    /// Files that are not line records: an end of the session would import them whole.
438    pub whole_files: usize,
439}
440
441/// How many files a session holds and their bytes, read from the folder alone (no file is opened).
442pub fn measure(files: &SessionFiles) -> Result<(usize, u64), String> {
443    let members = members(files)?;
444    let bytes = members.iter().map(|m| std::fs::metadata(&m.path).map(|x| x.len()).unwrap_or(0)).sum();
445    Ok((members.len(), bytes))
446}
447
448/// The proof of [`end_session`] and nothing after it: the same reads, the same match, no write. An `Err` is a session
449/// whose proof could not be made.
450pub fn prove_session(files: &SessionFiles, read: &[&dyn Zone]) -> Result<ProofCounts, String> {
451    require_open_matching(&withhold::health().mode)?;
452    let members = members(files)?;
453    let index = index_store(read, &files.sid)?;
454    let mut out = ProofCounts::default();
455    for m in &members {
456        let p = if is_lines_file(m) { prove_lines(m, &index)? } else { whole_proof(m)? };
457        out.files += 1;
458        out.bytes += std::fs::metadata(&m.path).map(|x| x.len()).unwrap_or(0);
459        out.records += p.records;
460        out.matched += p.matched;
461        out.unmatched += p.unmatched.len();
462        out.whole_files += usize::from(p.whole);
463    }
464    Ok(out)
465}
466
467fn import(files: &SessionFiles, zone: &dyn Zone, proofs: &[FileProof]) -> Result<(), String> {
468    let mut sidecar = Vec::new();
469    for p in proofs {
470        let name = import_name(&files.sid, &p.rel);
471        if p.whole {
472            import_whole(zone, &name, &p.path)?;
473        } else if !p.unmatched.is_empty() {
474            import_lines(zone, &name, &p.unmatched)?;
475        }
476        sidecar.extend(p.sidecar.iter().map(|(n, f)| sidecar_line(&files.sid, &p.rel, *n, f)));
477    }
478    if sidecar.is_empty() {
479        return Ok(());
480    }
481    let held = lines_set(&zone.read_all(SIDECAR_FILE)?);
482    let fresh: Vec<&String> = sidecar.iter().filter(|l| !held.contains(*l)).collect();
483    let mut out = String::new();
484    for l in fresh {
485        out.push_str(l);
486        out.push('\n');
487    }
488    zone.append(SIDECAR_FILE, out.as_bytes())
489}
490
491/// The second look: what was imported reads back equal to what the files hold.
492fn verify(files: &SessionFiles, zone: &dyn Zone, proofs: &[FileProof]) -> Result<(), String> {
493    let held_sidecar = lines_set(&zone.read_all(SIDECAR_FILE)?);
494    for p in proofs {
495        let name = import_name(&files.sid, &p.rel);
496        if p.whole {
497            if p.want != Some(zone_digest(zone, &name)?) {
498                return Err("an imported file does not read back equal".to_string());
499            }
500        } else if !p.unmatched.is_empty() {
501            let held = lines_set(&zone.read_all(&name)?);
502            if p.unmatched.iter().any(|l| !held.contains(l)) {
503                return Err("an imported record does not read back".to_string());
504            }
505        }
506        if p.sidecar.iter().any(|(n, f)| !held_sidecar.contains(&sidecar_line(&files.sid, &p.rel, *n, f))) {
507            return Err("a sidecar line does not read back".to_string());
508        }
509    }
510    Ok(())
511}
512
513/// Overwrite a file with zeros, sync it, let `hook` see it, and unlink it. The file is opened once, and what it holds
514/// must still be what the proof read (`expect`): a file that grew or changed, or a link put in its place, is refused.
515fn erase_file(path: &Path, expect: Sum, hook: &mut dyn FnMut(&Path, u64)) -> Result<(), String> {
516    use std::io::{Seek, SeekFrom};
517    if !std::fs::symlink_metadata(path).map_err(|e| e.to_string())?.is_file() {
518        return Err("a file of the session changed into something that is not a file".to_string());
519    }
520    let mut f = std::fs::OpenOptions::new().read(true).write(true).open(path).map_err(|e| e.to_string())?;
521    let mut h = Sha256::new();
522    let mut size = 0u64;
523    let mut buf = vec![0u8; 1 << 20];
524    loop {
525        let n = f.read(&mut buf).map_err(|e| e.to_string())?;
526        if n == 0 {
527            break;
528        }
529        size += n as u64;
530        h.update(&buf[..n]);
531    }
532    if (size, <[u8; 32]>::from(h.finalize())) != expect {
533        return Err("a file of the session changed after it was proved".to_string());
534    }
535    f.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
536    let zeros = vec![0u8; 64 << 10];
537    let mut left = size;
538    while left > 0 {
539        let n = left.min(zeros.len() as u64) as usize;
540        f.write_all(&zeros[..n]).map_err(|e| e.to_string())?;
541        left -= n as u64;
542    }
543    f.sync_all().map_err(|e| e.to_string())?;
544    drop(f);
545    hook(path, size);
546    std::fs::remove_file(path).map_err(|e| e.to_string())
547}
548
549/// Remove the files the proof read, by session id: each overwritten with zeros and then unlinked, then the session's
550/// folders. It names only `<sid>.jsonl` and `<sid>/` under the project folder and follows no link. A file that was
551/// added, is missing, or no longer holds what the proof read stops it **before any file is touched**. Returns how
552/// many files it removed.
553fn remove_proved(files: &SessionFiles, proved: &[(PathBuf, Sum)], held: &dyn Hold, erase: &mut dyn FnMut(&Path, u64)) -> Result<usize, String> {
554    held.still_held()?;
555    let now = members(files)?;
556    let same = now.len() == proved.len() && now.iter().zip(proved).all(|(m, (p, _))| &m.path == p);
557    if !same {
558        return Err("the files of the session changed after they were proved".to_string());
559    }
560    for (path, digest) in proved {
561        if file_digest(path)? != *digest {
562            return Err("a file of the session changed after it was proved".to_string());
563        }
564    }
565    for (path, digest) in proved {
566        held.still_held()?;
567        erase_file(path, *digest, erase)?;
568    }
569    remove_dirs(&files.folder);
570    Ok(proved.len())
571}
572
573/// Remove the folder and its empty subfolders, deepest first; one that is not empty stays.
574fn remove_dirs(dir: &Path) {
575    let Ok(entries) = std::fs::read_dir(dir) else { return };
576    for e in entries.flatten() {
577        if std::fs::symlink_metadata(e.path()).is_ok_and(|m| m.is_dir()) {
578            remove_dirs(&e.path());
579        }
580    }
581    let _ = std::fs::remove_dir(dir);
582}
583
584#[cfg(test)]
585#[path = "provider_tests.rs"]
586mod tests;