Skip to main content

agentmux_srv_core/backend/attachments/
store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The on-disk attachment store: content-addressed originals, derived files,
5//! and the retention sweep. SPEC_AGENT_PANE_IMAGE_ATTACHMENTS_2026_09_26.md §6.3.
6//!
7//! ```text
8//! <root>/blobs/ab/<sha256>.<ext>       original bytes
9//! <root>/derived/ab/<sha256>.<fp>.thumb.<ext>
10//! <root>/derived/ab/<sha256>.<fp>.send.<ext>
11//! <root>/derived/ab/<sha256>.<fp>.json   StoredMeta
12//! <root>/derived/ab/<sha256>.sent        marker: sent to an agent at least once
13//! <root>/incoming/<uuid>.part          in-flight copy / upload
14//! <root>/sessions/<sha256(key)>.json     base64 inlined into one Claude session
15//! <root>/derived/ab/<sha256>.<fp>.text.txt  text version of a document
16//! <root>/named/<sha256>/<file name>     per-delivery copy of the original
17//! ```
18//!
19//! `<fp>` is the transform fingerprint ([`fingerprint`]): derived bytes
20//! depend on the send edge and the pipeline, not only on the original, so
21//! a settings change re-derives instead of reusing stale files.
22
23use std::io::{Read, Write};
24use std::path::{Path, PathBuf};
25use std::time::{Duration, SystemTime};
26
27use serde::{Deserialize, Serialize};
28use sha2::{Digest, Sha256};
29
30use super::extract;
31use super::kind::{self, FileKind};
32use super::process::{self, Derived};
33use crate::backend::rpc_types::AttachmentInfo;
34
35/// Bump when the derive pipeline's output changes, so existing derived
36/// files stop being reused.
37pub const DERIVE_VERSION: u32 = 1;
38
39/// The key derived files are stored under for a given send edge.
40pub fn fingerprint(send_max_edge: u32) -> String {
41    format!("v{DERIVE_VERSION}-e{send_max_edge}")
42}
43
44/// `incoming/` files older than this are leftovers from a crash or a
45/// cancelled copy.
46const INCOMING_MAX_AGE: Duration = Duration::from_secs(60 * 60);
47
48/// The shortest a file is kept, whatever the retention setting: the hold's 24 h and an hour's margin.
49pub const HELD_FILES_FLOOR: Duration = Duration::from_secs(25 * 60 * 60);
50
51/// Attachments never sent to an agent (drafts, abandoned or lost on restart)
52/// are kept at most this long, instead of the full retention window.
53pub const UNSENT_MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
54
55/// Hex SHA-256, lowercase. Every public entry point that turns an id into a
56/// path validates it with this first, so an id can never carry a separator.
57pub fn is_valid_id(id: &str) -> bool {
58    id.len() == 64
59        && id
60            .bytes()
61            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
62}
63
64/// What `derived/<id>.json` records about an attachment.
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66pub struct StoredMeta {
67    pub v: u32,
68    pub mime: String,
69    pub ext: String,
70    pub bytes: u64,
71    pub width: u32,
72    pub height: u32,
73    pub send_mime: String,
74    pub send_ext: String,
75    pub send_bytes: u64,
76    pub send_width: u32,
77    pub send_height: u32,
78    pub thumb_mime: String,
79    pub thumb_ext: String,
80    #[serde(default)]
81    pub first_frame_only: bool,
82    // ── Any-file attachments (SPEC_AGENT_PANE_FILE_ATTACHMENTS_2026_09_26.md) ──
83    // Absent in metadata written before files existed: those are images.
84    /// `FileKind::as_str`: image, svg, text, pdf, word, excel, …
85    #[serde(default = "default_kind")]
86    pub kind: String,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub page_count: Option<u32>,
89    /// Extension of the derived text version (`text.<ext>`), if one exists.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub text_ext: Option<String>,
92    #[serde(default)]
93    pub text_bytes: u64,
94    /// Why there is no text version, when one was expected.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub text_note: Option<String>,
97    #[serde(default)]
98    pub macros: bool,
99}
100
101fn default_kind() -> String {
102    "image".to_string()
103}
104
105impl StoredMeta {
106    pub fn is_image(&self) -> bool {
107        self.kind == "image"
108    }
109
110    pub fn to_info(&self, id: &str, name: &str) -> AttachmentInfo {
111        AttachmentInfo {
112            id: id.to_string(),
113            name: name.to_string(),
114            mime: self.mime.clone(),
115            bytes: self.bytes,
116            width: self.width,
117            height: self.height,
118            send_mime: self.send_mime.clone(),
119            send_bytes: self.send_bytes,
120            send_width: self.send_width,
121            send_height: self.send_height,
122            first_frame_only: self.first_frame_only,
123            kind: self.kind.clone(),
124            page_count: self.page_count,
125            text_bytes: self.text_bytes,
126            text_note: self.text_note.clone(),
127            macros: self.macros,
128        }
129    }
130}
131
132/// Which stored file to serve.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Kind {
135    Original,
136    /// The tile's preview: the image thumbnail, a text file's first lines,
137    /// or an SVG itself.
138    Thumb,
139    Send,
140    /// The extracted text version of a document.
141    Text,
142}
143
144impl Kind {
145    pub fn parse(s: &str) -> Option<Self> {
146        match s {
147            "original" => Some(Kind::Original),
148            "thumb" => Some(Kind::Thumb),
149            "send" => Some(Kind::Send),
150            "text" => Some(Kind::Text),
151            _ => None,
152        }
153    }
154}
155
156#[derive(Debug, Clone)]
157pub struct Store {
158    root: PathBuf,
159}
160
161impl Store {
162    pub fn new(root: PathBuf) -> Self {
163        Self { root }
164    }
165
166    pub fn root(&self) -> &Path {
167        &self.root
168    }
169
170    /// Create the directory tree, owner-only.
171    pub fn ensure_dirs(&self) -> std::io::Result<()> {
172        std::fs::create_dir_all(&self.root)?;
173        let _ = agentmux_common::data_paths::ensure_owner_only_dir(&self.root);
174        for sub in ["blobs", "derived", "incoming", "sessions"] {
175            std::fs::create_dir_all(self.root.join(sub))?;
176        }
177        Ok(())
178    }
179
180    fn session_path(&self, key: &str) -> PathBuf {
181        let hashed = hex::encode(Sha256::digest(key.as_bytes()));
182        self.root.join("sessions").join(format!("{hashed}.json"))
183    }
184
185    /// Base64 bytes already inlined into the Claude session `key`. Kept on
186    /// disk so a restart doesn't reset it: Claude Code stores every inline
187    /// image in its own session transcript, and this is what bounds that.
188    pub fn session_inline_bytes(&self, key: &str) -> u64 {
189        std::fs::read_to_string(self.session_path(key))
190            .ok()
191            .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
192            .and_then(|v| v.get("bytes").and_then(|b| b.as_u64()))
193            .unwrap_or(0)
194    }
195
196    /// Fold the counter kept under `from` into `to` and remove `from`. A new
197    /// Claude session has no id on its first turn, so that turn is counted
198    /// under a per-block key; once the id is known it belongs to the session.
199    pub fn adopt_session_inline_bytes(&self, from: &str, to: &str) {
200        let carried = self.session_inline_bytes(from);
201        if carried == 0 {
202            return;
203        }
204        self.add_session_inline_bytes(to, carried);
205        let _ = std::fs::remove_file(self.session_path(from));
206    }
207
208    /// Take back bytes counted for a message that wasn't delivered.
209    pub fn refund_session_inline_bytes(&self, key: &str, bytes: u64) {
210        let now = self.session_inline_bytes(key);
211        if bytes == 0 || now == 0 {
212            return;
213        }
214        let _ = write_atomic(
215            &self.session_path(key),
216            serde_json::json!({ "bytes": now.saturating_sub(bytes) }).to_string().as_bytes(),
217        );
218    }
219
220    pub fn add_session_inline_bytes(&self, key: &str, bytes: u64) {
221        if bytes == 0 {
222            return;
223        }
224        let total = self.session_inline_bytes(key).saturating_add(bytes);
225        let path = self.session_path(key);
226        if let Some(dir) = path.parent() {
227            let _ = std::fs::create_dir_all(dir);
228        }
229        let _ = write_atomic(
230            &path,
231            serde_json::json!({ "bytes": total }).to_string().as_bytes(),
232        );
233    }
234
235    fn shard(id: &str) -> &str {
236        &id[..2]
237    }
238
239    pub fn blob_path(&self, id: &str, ext: &str) -> PathBuf {
240        self.root
241            .join("blobs")
242            .join(Self::shard(id))
243            .join(format!("{id}.{ext}"))
244    }
245
246    fn derived_path(&self, id: &str, fp: &str, suffix: &str) -> PathBuf {
247        self.root
248            .join("derived")
249            .join(Self::shard(id))
250            .join(format!("{id}.{fp}.{suffix}"))
251    }
252
253    fn meta_path(&self, id: &str, fp: &str) -> PathBuf {
254        self.derived_path(id, fp, "json")
255    }
256
257    /// The stored original for `id` and what kind of file it is.
258    pub fn find_blob(&self, id: &str) -> Option<(PathBuf, FileKind)> {
259        if !is_valid_id(id) {
260            return None;
261        }
262        let path = self.existing_blob(id)?;
263        // The blob's own name carries the extension it was stored with.
264        let name = path.file_name()?.to_string_lossy().into_owned();
265        let kind = kind::classify(&path, &name).ok()?;
266        Some((path, kind))
267    }
268
269    /// Copy the original of `id` into `dir` as `name`, with the same copy a
270    /// drop makes (`agentmux_common::copy_into_dir`): the name kept valid,
271    /// dotfiles included, and de-conflicted exclusively. For container panes,
272    /// whose agents can't see the store
273    /// (SPEC_AGENT_PANE_FILE_ATTACHMENTS_2026_09_26.md §7).
274    pub fn copy_original_to(&self, id: &str, dir: &Path, name: &str) -> std::io::Result<PathBuf> {
275        if !is_valid_id(id) {
276            return Err(std::io::Error::new(
277                std::io::ErrorKind::InvalidInput,
278                "invalid attachment id",
279            ));
280        }
281        let blob = self.existing_blob(id).ok_or_else(|| {
282            std::io::Error::new(std::io::ErrorKind::NotFound, "attachment not found")
283        })?;
284        if !dir.is_dir() {
285            return Err(std::io::Error::new(
286                std::io::ErrorKind::NotFound,
287                "working folder not found",
288            ));
289        }
290        use agentmux_common::copy_into_dir::{copy_into_dir, CopyControl};
291        copy_into_dir(&blob, dir, name, &CopyControl::default())
292    }
293
294    /// The stored original and its MIME type, whatever kind it is.
295    pub fn original(&self, id: &str) -> Option<(PathBuf, String)> {
296        let (path, kind) = self.find_blob(id)?;
297        let mime = match kind {
298            FileKind::Image(f) => process::mime_of(f).to_string(),
299            _ => mime_for(kind, &blob_ext(&path)),
300        };
301        Some((path, mime))
302    }
303
304    /// An existing original for `id`, whatever extension it was stored with.
305    fn existing_blob(&self, id: &str) -> Option<PathBuf> {
306        let dir = self.root.join("blobs").join(Self::shard(id));
307        let prefix = format!("{id}.");
308        std::fs::read_dir(dir)
309            .ok()?
310            .filter_map(Result::ok)
311            .map(|e| e.path())
312            .find(|p| {
313                p.file_name()
314                    .and_then(|n| n.to_str())
315                    .is_some_and(|n| n.starts_with(&prefix))
316            })
317    }
318
319    fn named_path(&self, id: &str, name: &str) -> PathBuf {
320        self.root.join("named").join(id).join(safe_file_name(name))
321    }
322
323    /// A copy of the original named as the user's file, for delivery
324    /// (agents recognise files by extension, and the real name reads
325    /// better than a hash). A real copy, never a hard link: an agent that
326    /// edits the file it was given must not change the content-addressed
327    /// original. Re-copied on every delivery, so an earlier edit never
328    /// reaches the next message.
329    pub fn named_link(&self, id: &str, name: &str) -> Option<PathBuf> {
330        if !is_valid_id(id) {
331            return None;
332        }
333        let target = self.existing_blob(id)?;
334        let link = self.named_path(id, name);
335        std::fs::create_dir_all(link.parent()?).ok()?;
336        let tmp = link.with_extension(format!("part-{}", uuid::Uuid::new_v4()));
337        std::fs::copy(&target, &tmp).ok()?;
338        if std::fs::rename(&tmp, &link).is_err() {
339            let _ = std::fs::remove_file(&tmp);
340            // The old copy may be open in an agent's editor (Windows keeps it
341            // locked); it still holds the right name, so keep serving it.
342            return link.is_file().then_some(link);
343        }
344        Some(link)
345    }
346
347    pub fn new_incoming_path(&self) -> PathBuf {
348        self.root
349            .join("incoming")
350            .join(format!("{}.part", uuid::Uuid::new_v4()))
351    }
352
353    /// Stored metadata for fingerprint `fp`, or `None` when the id is
354    /// invalid, not in the store, or not yet derived for `fp`.
355    pub fn meta(&self, id: &str, fp: &str) -> Option<StoredMeta> {
356        if !is_valid_id(id) {
357            return None;
358        }
359        let text = std::fs::read_to_string(self.meta_path(id, fp)).ok()?;
360        let meta: StoredMeta = serde_json::from_str(&text).ok()?;
361        // Every file it names must still exist; the sweep can race a lookup.
362        let complete = self.blob_path(id, &meta.ext).is_file()
363            && self.meta_files(id, fp, &meta).iter().all(|p| p.is_file());
364        complete.then_some(meta)
365    }
366
367    /// The derived files `meta` says exist (not the original).
368    fn meta_files(&self, id: &str, fp: &str, meta: &StoredMeta) -> Vec<PathBuf> {
369        let mut out = Vec::new();
370        if meta.is_image() {
371            out.push(self.derived_path(id, fp, &format!("send.{}", meta.send_ext)));
372        }
373        if !meta.thumb_ext.is_empty() {
374            out.push(self.derived_path(id, fp, &format!("thumb.{}", meta.thumb_ext)));
375        }
376        if let Some(ext) = &meta.text_ext {
377            out.push(self.derived_path(id, fp, &format!("text.{ext}")));
378        }
379        out
380    }
381
382    /// Path and MIME type of one stored file. Non-images have no separate
383    /// send-copy (the original is sent) and, except text, no thumbnail file
384    /// (an SVG is its own thumbnail).
385    pub fn file(&self, id: &str, fp: &str, kind: Kind) -> Option<(PathBuf, String)> {
386        let meta = self.meta(id, fp)?;
387        let original = (self.blob_path(id, &meta.ext), meta.mime.clone());
388        Some(match kind {
389            Kind::Original => original,
390            Kind::Send if !meta.is_image() => original,
391            Kind::Send => (
392                self.derived_path(id, fp, &format!("send.{}", meta.send_ext)),
393                meta.send_mime,
394            ),
395            Kind::Thumb if meta.kind == "svg" => original,
396            Kind::Thumb if meta.thumb_ext.is_empty() => return None,
397            Kind::Thumb => (
398                self.derived_path(id, fp, &format!("thumb.{}", meta.thumb_ext)),
399                meta.thumb_mime,
400            ),
401            Kind::Text => (
402                self.derived_path(id, fp, &format!("text.{}", meta.text_ext.as_deref()?)),
403                "text/plain; charset=utf-8".to_string(),
404            ),
405        })
406    }
407
408    /// Mark an attachment as used now, so the retention sweep keeps it.
409    pub fn touch(&self, id: &str, fp: &str) {
410        let Some(meta) = self.meta(id, fp) else {
411            return;
412        };
413        let now = filetime_now();
414        let mut files = vec![
415            self.blob_path(id, &meta.ext),
416            self.meta_path(id, fp),
417            self.sent_marker(id),
418        ];
419        files.extend(self.meta_files(id, fp, &meta));
420        for p in files {
421            let _ = set_mtime(&p, now);
422        }
423    }
424
425    fn sent_marker(&self, id: &str) -> PathBuf {
426        self.root
427            .join("derived")
428            .join(Self::shard(id))
429            .join(format!("{id}.sent"))
430    }
431
432    /// Record that an attachment went to an agent, which moves it from the
433    /// 7-day unsent window to the full retention window.
434    pub fn mark_sent(&self, id: &str) {
435        if !is_valid_id(id) {
436            return;
437        }
438        let marker = self.sent_marker(id);
439        if let Some(dir) = marker.parent() {
440            let _ = std::fs::create_dir_all(dir);
441        }
442        let _ = std::fs::write(&marker, b"");
443    }
444
445    fn is_sent(&self, id: &str) -> bool {
446        self.sent_marker(id).is_file()
447    }
448
449    /// Remove the original of an attachment that has no metadata under any
450    /// fingerprint, i.e. one whose processing failed after [`Self::place`]
451    /// stored it. Without this, a file that sniffs as an image but won't
452    /// decode would sit in `blobs/` until the retention sweep.
453    pub fn discard_if_unprocessed(&self, id: &str) {
454        if !is_valid_id(id) {
455            return;
456        }
457        let prefix = format!("{id}.");
458        let names = |sub: &str| -> Vec<PathBuf> {
459            std::fs::read_dir(self.root.join(sub).join(Self::shard(id)))
460                .map(|rd| {
461                    rd.filter_map(Result::ok)
462                        .map(|e| e.path())
463                        .filter(|p| {
464                            p.file_name()
465                                .and_then(|n| n.to_str())
466                                .is_some_and(|n| n.starts_with(&prefix))
467                        })
468                        .collect()
469                })
470                .unwrap_or_default()
471        };
472        let processed = names("derived")
473            .iter()
474            .any(|p| p.extension().is_some_and(|e| e == "json"));
475        if processed {
476            return;
477        }
478        for blob in names("blobs") {
479            let _ = std::fs::remove_file(blob);
480        }
481    }
482
483    /// Copy `src` into `incoming/`, hashing as it goes. `on_progress` is
484    /// called with the bytes copied so far; returning `false` cancels.
485    /// Returns the incoming path and the hex SHA-256.
486    pub fn copy_in(
487        &self,
488        src: &Path,
489        mut on_progress: impl FnMut(u64) -> bool,
490    ) -> std::io::Result<(PathBuf, String, u64)> {
491        let mut input = std::fs::File::open(src)?;
492        let tmp = self.new_incoming_path();
493        let result = (|| {
494            let mut out = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
495            let mut hasher = Sha256::new();
496            let mut buf = vec![0u8; 1024 * 1024];
497            let mut done = 0u64;
498            loop {
499                let n = input.read(&mut buf)?;
500                if n == 0 {
501                    break;
502                }
503                hasher.update(&buf[..n]);
504                out.write_all(&buf[..n])?;
505                done += n as u64;
506                if !on_progress(done) {
507                    return Err(std::io::Error::new(
508                        std::io::ErrorKind::Interrupted,
509                        "cancelled",
510                    ));
511                }
512            }
513            out.flush()?;
514            Ok((hex::encode(hasher.finalize()), done))
515        })();
516        match result {
517            Ok((id, n)) => Ok((tmp, id, n)),
518            Err(e) => {
519                let _ = std::fs::remove_file(&tmp);
520                Err(e)
521            }
522        }
523    }
524
525    /// Move a hashed file from `incoming/` into `blobs/`, or drop it when the
526    /// same bytes are already stored (under whatever extension they were
527    /// stored with). `name` is the user's file name, used only to classify.
528    /// Returns the blob path and what kind of file it is.
529    pub fn place(
530        &self,
531        incoming: &Path,
532        id: &str,
533        name: &str,
534    ) -> Result<(PathBuf, FileKind), process::ProcessError> {
535        let cleanup = || {
536            let _ = std::fs::remove_file(incoming);
537        };
538        if let Some(existing) = self.existing_blob(id) {
539            cleanup();
540            let _ = set_mtime(&existing, filetime_now());
541            let stored_name = existing
542                .file_name()
543                .map(|n| n.to_string_lossy().into_owned())
544                .unwrap_or_default();
545            let kind = kind::classify(&existing, &stored_name).map_err(io_error)?;
546            return Ok((existing, kind));
547        }
548        let kind = kind::classify(incoming, name).map_err(|e| {
549            cleanup();
550            io_error(e)
551        })?;
552        let blob = self.blob_path(id, &stored_extension(kind, name));
553        let placed = (|| {
554            std::fs::create_dir_all(blob.parent().unwrap())?;
555            std::fs::rename(incoming, &blob)
556        })();
557        placed.map_err(|e| {
558            cleanup();
559            io_error(e)
560        })?;
561        Ok((blob, kind))
562    }
563
564    /// [`Self::place`] without reading the file: no classification (which opens
565    /// a ZIP's directory) and no derivation. The blob keeps the user's
566    /// extension only when it is one a kind would keep, else `bin`; what it is
567    /// is found when something opens it (`find_blob`).
568    pub fn place_undecoded(&self, incoming: &Path, id: &str, name: &str) -> Result<(), process::ProcessError> {
569        let cleanup = || {
570            let _ = std::fs::remove_file(incoming);
571        };
572        if let Some(existing) = self.existing_blob(id) {
573            cleanup();
574            let _ = set_mtime(&existing, filetime_now());
575            // The marker lives as long as the file does.
576            let _ = set_mtime(&self.unread_path(id), filetime_now());
577            return Ok(());
578        }
579        let blob = self.blob_path(id, &undecoded_extension(name));
580        let placed = (|| {
581            std::fs::create_dir_all(blob.parent().unwrap())?;
582            std::fs::rename(incoming, &blob)
583        })();
584        placed.map_err(|e| {
585            cleanup();
586            io_error(e)
587        })?;
588        self.mark_unread(id);
589        Ok(())
590    }
591
592    fn unread_path(&self, id: &str) -> PathBuf {
593        self.root.join("unread").join(id)
594    }
595
596    /// Record that nothing has been derived from the original of `id` and
597    /// that passive requests (a pane drawing its tile) must not derive it.
598    fn mark_unread(&self, id: &str) {
599        let path = self.unread_path(id);
600        if let Some(dir) = path.parent() {
601            let _ = std::fs::create_dir_all(dir);
602        }
603        let _ = std::fs::write(path, b"");
604    }
605
606    /// Whether `id` was stored without anything read from it and not opened since.
607    pub fn is_unread(&self, id: &str) -> bool {
608        is_valid_id(id) && self.unread_path(id).is_file()
609    }
610
611    fn clear_unread(&self, id: &str) {
612        let _ = std::fs::remove_file(self.unread_path(id));
613    }
614
615    /// The size of the stored original of `id`, if there is one. Reads nothing from it.
616    pub fn blob_len(&self, id: &str) -> Option<u64> {
617        if !is_valid_id(id) {
618            return None;
619        }
620        std::fs::metadata(self.existing_blob(id)?).ok().map(|m| m.len())
621    }
622
623    /// Whether the original of `id` is stored. Reads nothing from it.
624    pub fn has_blob(&self, id: &str) -> bool {
625        is_valid_id(id) && self.existing_blob(id).is_some()
626    }
627
628    /// Derive whatever `kind` needs and write the metadata. Images go through
629    /// the image pipeline (decode, thumbnail, send-copy); other files get a
630    /// text preview, a text version or PDF facts.
631    pub fn derive_and_save(
632        &self,
633        id: &str,
634        blob: &Path,
635        kind: FileKind,
636        name: &str,
637        send_max_edge: u32,
638    ) -> Result<StoredMeta, process::ProcessError> {
639        let meta = match kind {
640            FileKind::Image(format) => self.derive_image(id, blob, format, send_max_edge),
641            _ => self.derive_file(id, blob, kind, name, send_max_edge),
642        }?;
643        self.clear_unread(id);
644        Ok(meta)
645    }
646
647    /// Decode a stored image and write its thumbnail, send-copy and
648    /// metadata under fingerprint `fingerprint(send_max_edge)`.
649    fn derive_image(
650        &self,
651        id: &str,
652        blob: &Path,
653        format: image::ImageFormat,
654        send_max_edge: u32,
655    ) -> Result<StoredMeta, process::ProcessError> {
656        let fp = fingerprint(send_max_edge);
657        let derived: Derived = process::derive(blob, format, send_max_edge)?;
658        let bytes = std::fs::metadata(blob).map(|m| m.len()).map_err(io_error)?;
659        let meta = StoredMeta {
660            v: DERIVE_VERSION,
661            mime: process::mime_of(format).to_string(),
662            ext: blob_ext(blob),
663            bytes,
664            width: derived.width,
665            height: derived.height,
666            send_mime: process::mime_of(derived.send.format).to_string(),
667            send_ext: process::ext_of(derived.send.format).to_string(),
668            send_bytes: derived.send.bytes.len() as u64,
669            send_width: derived.send.width,
670            send_height: derived.send.height,
671            thumb_mime: process::mime_of(derived.thumb.format).to_string(),
672            thumb_ext: process::ext_of(derived.thumb.format).to_string(),
673            first_frame_only: derived.first_frame_only,
674            kind: default_kind(),
675            page_count: None,
676            text_ext: None,
677            text_bytes: 0,
678            text_note: None,
679            macros: false,
680        };
681        let write_all = || -> std::io::Result<()> {
682            let meta_path = self.meta_path(id, &fp);
683            std::fs::create_dir_all(meta_path.parent().unwrap())?;
684            write_atomic(
685                &self.derived_path(id, &fp, &format!("send.{}", meta.send_ext)),
686                &derived.send.bytes,
687            )?;
688            write_atomic(
689                &self.derived_path(id, &fp, &format!("thumb.{}", meta.thumb_ext)),
690                &derived.thumb.bytes,
691            )?;
692            // Metadata last: its presence is what makes the attachment visible.
693            write_atomic(&meta_path, serde_json::to_string(&meta).unwrap().as_bytes())
694        };
695        write_all().map_err(io_error)?;
696        Ok(meta)
697    }
698
699    /// Metadata and derived files for a non-image attachment: a preview for
700    /// text, a text version for Office documents and PDFs, a page count and
701    /// macro flag where they apply. Failures to extract never fail the
702    /// attachment; it is still sent by path, with a note.
703    fn derive_file(
704        &self,
705        id: &str,
706        blob: &Path,
707        kind: FileKind,
708        name: &str,
709        send_max_edge: u32,
710    ) -> Result<StoredMeta, process::ProcessError> {
711        let fp = fingerprint(send_max_edge);
712        let bytes = std::fs::metadata(blob).map(|m| m.len()).map_err(io_error)?;
713        let ext = blob_ext(blob);
714        let mime = mime_for(kind, &ext);
715        let mut meta = StoredMeta {
716            v: DERIVE_VERSION,
717            mime: mime.clone(),
718            ext: ext.clone(),
719            bytes,
720            width: 0,
721            height: 0,
722            send_mime: mime,
723            send_ext: ext,
724            send_bytes: bytes,
725            send_width: 0,
726            send_height: 0,
727            thumb_mime: String::new(),
728            thumb_ext: String::new(),
729            first_frame_only: false,
730            kind: kind.as_str().to_string(),
731            page_count: None,
732            text_ext: None,
733            text_bytes: 0,
734            text_note: None,
735            macros: false,
736        };
737        let mut thumb: Option<String> = None;
738        let mut text: Option<String> = None;
739        match kind {
740            FileKind::Text => thumb = extract::text_preview(blob).ok(),
741            FileKind::Pdf => {
742                let facts = extract::pdf_facts_isolated(blob, name);
743                meta.page_count = facts.pages;
744                if facts.text.is_none() {
745                    meta.text_note = Some(
746                        "no text could be read from this PDF (it may be scanned or protected)"
747                            .into(),
748                    );
749                }
750                text = facts.text;
751            }
752            FileKind::Word | FileKind::Excel | FileKind::PowerPoint => {
753                meta.macros = extract::has_macros(blob);
754                match extract::document_text_isolated(blob, kind, name) {
755                    Ok(Some(t)) => text = Some(t),
756                    Ok(None) => {
757                        meta.text_note = Some(match meta.ext.as_str() {
758                            "doc" => "no text version; save it as .docx".to_string(),
759                            "ppt" => "no text version; save it as .pptx".to_string(),
760                            _ => "no text version for this format".to_string(),
761                        })
762                    }
763                    Err(e) => meta.text_note = Some(format!("no text version: {e}")),
764                }
765            }
766            _ => {}
767        }
768        let write_all = |meta: &mut StoredMeta| -> std::io::Result<()> {
769            let meta_path = self.meta_path(id, &fp);
770            std::fs::create_dir_all(meta_path.parent().unwrap())?;
771            if let Some(t) = &thumb {
772                meta.thumb_ext = "txt".into();
773                meta.thumb_mime = "text/plain; charset=utf-8".into();
774                write_atomic(&self.derived_path(id, &fp, "thumb.txt"), t.as_bytes())?;
775            }
776            if let Some(t) = &text {
777                meta.text_ext = Some("txt".into());
778                meta.text_bytes = t.len() as u64;
779                write_atomic(&self.derived_path(id, &fp, "text.txt"), t.as_bytes())?;
780            }
781            write_atomic(
782                &meta_path,
783                serde_json::to_string(&*meta).unwrap().as_bytes(),
784            )
785        };
786        write_all(&mut meta).map_err(io_error)?;
787        Ok(meta)
788    }
789
790    /// [`Self::place`] then derive, reusing derived files when they exist.
791    /// Test convenience: the service calls the two steps separately so it
792    /// can reserve decode memory in between.
793    #[cfg(test)]
794    pub fn commit(
795        &self,
796        incoming: &Path,
797        id: &str,
798        send_max_edge: u32,
799    ) -> Result<StoredMeta, process::ProcessError> {
800        self.commit_named(incoming, id, "file.png", send_max_edge)
801    }
802
803    /// [`Self::commit`] with the user's file name (tests).
804    #[cfg(test)]
805    pub fn commit_named(
806        &self,
807        incoming: &Path,
808        id: &str,
809        name: &str,
810        send_max_edge: u32,
811    ) -> Result<StoredMeta, process::ProcessError> {
812        let (blob, kind) = self.place(incoming, id, name)?;
813        let fp = fingerprint(send_max_edge);
814        if let Some(meta) = self.meta(id, &fp) {
815            self.touch(id, &fp);
816            return Ok(meta);
817        }
818        self.derive_and_save(id, &blob, kind, name, send_max_edge)
819    }
820
821    /// Metadata for `id` under the current send edge, re-deriving from the
822    /// stored original when the fingerprint changed since it was processed.
823    /// Test helper: production code goes through `Service::ensure_derived`,
824    /// which applies the CPU and memory limits.
825    #[cfg(test)]
826    pub fn ensure_derived(&self, id: &str, send_max_edge: u32) -> Option<StoredMeta> {
827        let fp = fingerprint(send_max_edge);
828        if let Some(meta) = self.meta(id, &fp) {
829            return Some(meta);
830        }
831        let (blob, kind) = self.find_blob(id)?;
832        let name = blob.file_name()?.to_string_lossy().into_owned();
833        self.derive_and_save(id, &blob, kind, &name, send_max_edge)
834            .ok()
835    }
836
837    /// Delete the extracted-text cache of each attachment in `ids`, under every fingerprint (`<id>.<fp>.text.<ext>`).
838    /// The original and the other derived files stay: the next send finds the metadata incomplete and extracts the
839    /// text again ([`Self::meta`]). An id that is not an id names nothing. Returns how many files were removed.
840    pub fn remove_text_caches(&self, ids: &[String]) -> usize {
841        let mut removed = 0;
842        for id in ids.iter().filter(|id| is_valid_id(id)) {
843            let Ok(entries) = std::fs::read_dir(self.root.join("derived").join(Self::shard(id))) else { continue };
844            for e in entries.flatten() {
845                let name = e.file_name();
846                let is_cache = name.to_str().and_then(|n| n.strip_prefix(id.as_str())).and_then(|rest| rest.strip_prefix('.')).is_some_and(|rest| rest.split_once(".text.").is_some_and(|(fp, ext)| !fp.is_empty() && !fp.contains('.') && !ext.is_empty() && !ext.contains('.')));
847                if is_cache && e.file_type().is_ok_and(|t| t.is_file()) && std::fs::remove_file(e.path()).is_ok() {
848                    removed += 1;
849                }
850            }
851        }
852        removed
853    }
854
855    /// Delete attachment files unused for `retention` (or for
856    /// [`UNSENT_MAX_AGE`] when the attachment was never sent), and
857    /// `incoming/` leftovers older than an hour. Returns how many files were
858    /// removed.
859    pub fn sweep(&self, retention: Duration) -> usize {
860        let now = SystemTime::now();
861        // Never before a message holding a file could expire (`jekt_held::HELD_TTL_MS`): a file sent with
862        // a message held for an agent that can't work is delivered with it, up to a day later.
863        let retention = retention.max(HELD_FILES_FLOOR);
864        let unsent = UNSENT_MAX_AGE.min(retention);
865        let mut sent_cache: std::collections::HashMap<String, bool> =
866            std::collections::HashMap::new();
867        let mut removed = 0;
868        for sub in ["blobs", "derived", "incoming", "sessions", "named", "unread"] {
869            let dir = self.root.join(sub);
870            let Ok(entries) = walk_files(&dir) else {
871                continue;
872            };
873            for path in entries {
874                let max_age = if sub == "incoming" {
875                    INCOMING_MAX_AGE
876                } else if sub == "sessions" || sub == "named" {
877                    // Session counters are named by a hash; named links
878                    // exist only for sent attachments.
879                    retention
880                } else {
881                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
882                    match name.get(..64).filter(|id| is_valid_id(id)) {
883                        Some(id) => {
884                            let sent = *sent_cache
885                                .entry(id.to_string())
886                                .or_insert_with(|| self.is_sent(id));
887                            if sent {
888                                retention
889                            } else {
890                                unsent
891                            }
892                        }
893                        None => retention,
894                    }
895                };
896                let old = std::fs::metadata(&path)
897                    .and_then(|m| m.modified())
898                    .ok()
899                    .and_then(|t| now.duration_since(t).ok())
900                    .map(|age| age > max_age)
901                    .unwrap_or(false);
902                if old && std::fs::remove_file(&path).is_ok() {
903                    removed += 1;
904                    if sub == "named" {
905                        // Drop the per-id folder once its last link is gone.
906                        if let Some(dir) = path.parent() {
907                            let _ = std::fs::remove_dir(dir);
908                        }
909                    }
910                }
911            }
912        }
913        removed
914    }
915}
916
917/// The extension a new original is stored under. It follows the content
918/// where the content decides it (image formats, PDF, SVG, RTF), and
919/// otherwise the user's extension if it fits the kind (docx vs odt vs doc,
920/// mp3 vs wav, …). Text and unknown files are `bin`: the same bytes can
921/// arrive as notes.txt and script.py, and agents get a correctly named
922/// link per delivery instead (`named_link`).
923fn stored_extension(kind: FileKind, name: &str) -> String {
924    let user = kind::extension_of(name);
925    let pick = |allowed: &[&str], default: &str| -> String {
926        user.as_deref()
927            .filter(|e| allowed.contains(e))
928            .unwrap_or(default)
929            .to_string()
930    };
931    match kind {
932        FileKind::Image(f) => process::ext_of(f).to_string(),
933        FileKind::Svg => "svg".into(),
934        FileKind::Pdf => "pdf".into(),
935        FileKind::Word => pick(&["docx", "docm", "dotx", "odt", "doc", "rtf"], "docx"),
936        FileKind::Excel => pick(&["xlsx", "xlsm", "xlsb", "xls", "ods"], "xlsx"),
937        FileKind::PowerPoint => pick(&["pptx", "pptm", "ppsx", "odp", "ppt"], "pptx"),
938        FileKind::Archive => pick(
939            &["zip", "gz", "tgz", "tar", "7z", "rar", "bz2", "xz", "zst"],
940            "bin",
941        ),
942        FileKind::Audio => pick(
943            &[
944                "mp3", "wav", "flac", "m4a", "aac", "ogg", "oga", "opus", "wma", "aiff", "aif",
945            ],
946            "bin",
947        ),
948        FileKind::Video => pick(
949            &[
950                "mp4", "m4v", "mov", "webm", "mkv", "avi", "wmv", "flv", "mpg", "mpeg",
951            ],
952            "bin",
953        ),
954        FileKind::ImageFile => pick(&["heic", "heif", "avif"], "bin"),
955        FileKind::Text | FileKind::Other => "bin".into(),
956    }
957}
958
959/// The extension an original is stored under when nothing was read from it:
960/// the user's own when [`stored_extension`] would keep it for some kind
961/// (documents, PDF, SVG, archives, audio, video), else `bin`.
962fn undecoded_extension(name: &str) -> String {
963    let Some(user) = kind::extension_of(name) else {
964        return "bin".into();
965    };
966    let kept = [
967        FileKind::Svg,
968        FileKind::Pdf,
969        FileKind::Word,
970        FileKind::Excel,
971        FileKind::PowerPoint,
972        FileKind::Archive,
973        FileKind::Audio,
974        FileKind::Video,
975        FileKind::ImageFile,
976    ]
977    .into_iter()
978    .any(|k| stored_extension(k, name) == user);
979    if kept { user } else { "bin".into() }
980}
981
982/// The extension part of a stored blob's file name.
983fn blob_ext(blob: &Path) -> String {
984    blob.extension()
985        .map(|e| e.to_string_lossy().into_owned())
986        .unwrap_or_else(|| "bin".into())
987}
988
989/// MIME type of a non-image original.
990fn mime_for(kind: FileKind, ext: &str) -> String {
991    match (kind, ext) {
992        (FileKind::Svg, _) => "image/svg+xml",
993        (FileKind::Pdf, _) => "application/pdf",
994        (FileKind::Text, _) => "text/plain; charset=utf-8",
995        (_, "docx") => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
996        (_, "xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
997        (_, "pptx") => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
998        (_, "odt") => "application/vnd.oasis.opendocument.text",
999        (_, "ods") => "application/vnd.oasis.opendocument.spreadsheet",
1000        (_, "odp") => "application/vnd.oasis.opendocument.presentation",
1001        (_, "doc") => "application/msword",
1002        (_, "xls") => "application/vnd.ms-excel",
1003        (_, "ppt") => "application/vnd.ms-powerpoint",
1004        (_, "rtf") => "application/rtf",
1005        (_, "zip") => "application/zip",
1006        (FileKind::Audio, e) => return format!("audio/{e}"),
1007        (FileKind::Video, e) => return format!("video/{e}"),
1008        _ => "application/octet-stream",
1009    }
1010    .to_string()
1011}
1012
1013/// The attachments whose extracted text `text` names: a message tells the agent where the text version is
1014/// (`.../derived/<xx>/<id>.<fp>.text.<ext>`), so the session that was told holds that path. Ids only, each once, in
1015/// order of appearance; what it names is removed from this store only ([`Store::remove_text_caches`]).
1016pub fn text_cache_ids(text: &str) -> Vec<String> {
1017    static ID: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1018    let re = ID.get_or_init(|| regex::Regex::new(r"derived[/\\]+[0-9a-f]{2}[/\\]+([0-9a-f]{64})\.[A-Za-z0-9-]+\.text\.[A-Za-z0-9]+").expect("a fixed pattern"));
1019    let mut out: Vec<String> = Vec::new();
1020    for c in re.captures_iter(text) {
1021        let id = c[1].to_string();
1022        if !out.contains(&id) {
1023            out.push(id);
1024        }
1025    }
1026    out
1027}
1028
1029/// A user's file name made safe as a single path component: separators,
1030/// control characters and Windows-reserved characters replaced, leading
1031/// dots and trailing dots/spaces trimmed, length bounded.
1032pub fn safe_file_name(name: &str) -> String {
1033    let cleaned: String = name
1034        .chars()
1035        .map(|c| {
1036            if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') {
1037                '_'
1038            } else {
1039                c
1040            }
1041        })
1042        .collect();
1043    let trimmed = cleaned
1044        .trim_start_matches('.')
1045        .trim_end_matches(['.', ' '])
1046        .trim();
1047    let short: String = trimmed.chars().take(120).collect();
1048    if short.is_empty() {
1049        "file".to_string()
1050    } else {
1051        short
1052    }
1053}
1054
1055fn io_error(e: std::io::Error) -> process::ProcessError {
1056    process::ProcessError {
1057        code: "io",
1058        message: e.to_string(),
1059    }
1060}
1061
1062fn walk_files(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
1063    let mut out = Vec::new();
1064    for entry in std::fs::read_dir(dir)? {
1065        let entry = entry?;
1066        let ft = entry.file_type()?;
1067        if ft.is_dir() {
1068            if let Ok(mut inner) = walk_files(&entry.path()) {
1069                out.append(&mut inner);
1070            }
1071        } else if ft.is_file() {
1072            out.push(entry.path());
1073        }
1074    }
1075    Ok(out)
1076}
1077
1078fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1079    let tmp = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));
1080    std::fs::write(&tmp, bytes)?;
1081    std::fs::rename(&tmp, path).inspect_err(|_| {
1082        let _ = std::fs::remove_file(&tmp);
1083    })
1084}
1085
1086fn filetime_now() -> SystemTime {
1087    SystemTime::now()
1088}
1089
1090fn set_mtime(path: &Path, t: SystemTime) -> std::io::Result<()> {
1091    let f = std::fs::OpenOptions::new().write(true).open(path)?;
1092    f.set_modified(t)
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097    use super::*;
1098    use image::{DynamicImage, ImageFormat, Rgb, RgbImage};
1099
1100    fn store() -> (tempfile::TempDir, Store) {
1101        let dir = tempfile::tempdir().unwrap();
1102        let s = Store::new(dir.path().join("attachments"));
1103        s.ensure_dirs().unwrap();
1104        (dir, s)
1105    }
1106
1107    fn png(dir: &Path, name: &str, shade: u8) -> PathBuf {
1108        let p = dir.join(name);
1109        DynamicImage::ImageRgb8(RgbImage::from_pixel(40, 30, Rgb([shade, 0, 0])))
1110            .save_with_format(&p, ImageFormat::Png)
1111            .unwrap();
1112        p
1113    }
1114
1115    fn ingest(s: &Store, src: &Path) -> Result<(String, StoredMeta), process::ProcessError> {
1116        let (tmp, id, _) = s.copy_in(src, |_| true).unwrap();
1117        s.commit(&tmp, &id, 2000).map(|m| (id, m))
1118    }
1119
1120    #[test]
1121    fn copy_to_workdir_keeps_a_dotfile_name_and_deconflicts() {
1122        let (dir, s) = store();
1123        let src = png(dir.path(), "a.png", 10);
1124        let (id, _) = ingest(&s, &src).unwrap();
1125        let work = dir.path().join("work");
1126        std::fs::create_dir_all(&work).unwrap();
1127        let first = s.copy_original_to(&id, &work, ".env").unwrap();
1128        let second = s.copy_original_to(&id, &work, ".env").unwrap();
1129        assert_eq!(first.file_name().unwrap(), ".env");
1130        assert_eq!(second.file_name().unwrap(), ".env_1");
1131        assert_eq!(std::fs::read(&second).unwrap(), std::fs::read(&src).unwrap());
1132        assert!(s.copy_original_to(&id, &work.join("missing"), "x.png").is_err());
1133        assert!(s.copy_original_to("../escape", &work, "x.png").is_err());
1134    }
1135
1136    #[test]
1137    fn an_undecoded_file_is_placed_as_it_came_and_derived_only_when_opened() {
1138        let (dir, s) = store();
1139        // A ZIP that names itself a Word document: placing it must not open it.
1140        let src = dir.path().join("report.docx");
1141        let bytes = b"PK\x03\x04 not really a zip";
1142        std::fs::write(&src, bytes).unwrap();
1143        let (tmp, id, _) = s.copy_in(&src, |_| true).unwrap();
1144        s.place_undecoded(&tmp, &id, "report.docx").unwrap();
1145        let fp = fingerprint(2000);
1146        assert!(s.has_blob(&id) && s.blob_len(&id) == Some(bytes.len() as u64), "stored, sized from the file system");
1147        assert!(s.meta(&id, &fp).is_none(), "nothing derived");
1148        assert!(!tmp.exists(), "the incoming file moved");
1149        assert!(s.is_unread(&id), "marked, so passive requests leave it alone");
1150        assert!(s.blob_path(&id, "docx").is_file(), "an extension a kind keeps stays");
1151        // The same bytes again are not stored twice.
1152        let (tmp2, id2, _) = s.copy_in(&src, |_| true).unwrap();
1153        s.place_undecoded(&tmp2, &id2, "other.bin").unwrap();
1154        assert_eq!(id, id2);
1155        assert!(!tmp2.exists());
1156        // Opened: derived then.
1157        let note = dir.path().join("note.txt");
1158        std::fs::write(&note, b"plain words\n").unwrap();
1159        let (tmp3, id3, _) = s.copy_in(&note, |_| true).unwrap();
1160        s.place_undecoded(&tmp3, &id3, "note.txt").unwrap();
1161        assert!(s.meta(&id3, &fp).is_none());
1162        assert!(s.ensure_derived(&id3, 2000).is_some());
1163        assert!(s.meta(&id3, &fp).is_some());
1164        assert!(!s.is_unread(&id3), "derived: no longer unread");
1165    }
1166
1167    #[test]
1168    fn an_undecoded_file_keeps_only_an_extension_a_kind_would_keep() {
1169        for (name, ext) in [
1170            ("a.docx", "docx"),
1171            ("a.PDF", "pdf"),
1172            ("a.zip", "zip"),
1173            ("a.mp4", "mp4"),
1174            ("a.svg", "svg"),
1175            ("a.txt", "bin"),
1176            ("a.png", "bin"),
1177            ("a.exe", "bin"),
1178            ("noext", "bin"),
1179            ("a.not-an-ext", "bin"),
1180        ] {
1181            assert_eq!(undecoded_extension(name), ext, "{name}");
1182        }
1183    }
1184
1185    #[test]
1186    fn id_validation_rejects_anything_path_like() {
1187        assert!(is_valid_id(&"a".repeat(64)));
1188        assert!(!is_valid_id(&"A".repeat(64)));
1189        assert!(!is_valid_id("../../etc/passwd"));
1190        assert!(!is_valid_id(&format!("{}/", "a".repeat(63))));
1191        assert!(!is_valid_id(""));
1192    }
1193
1194    #[test]
1195    fn ingest_stores_original_thumb_send_and_meta() {
1196        let (dir, s) = store();
1197        let src = png(dir.path(), "a.png", 10);
1198        let (id, meta) = ingest(&s, &src).unwrap();
1199        let fp = fingerprint(2000);
1200        assert!(is_valid_id(&id));
1201        assert_eq!(meta.mime, "image/png");
1202        assert_eq!((meta.width, meta.height), (40, 30));
1203        assert_eq!(s.meta(&id, &fp), Some(meta));
1204        for kind in [Kind::Original, Kind::Thumb, Kind::Send] {
1205            assert!(s.file(&id, &fp, kind).unwrap().0.is_file());
1206        }
1207        // incoming/ is empty again.
1208        assert_eq!(
1209            std::fs::read_dir(s.root().join("incoming"))
1210                .unwrap()
1211                .count(),
1212            0
1213        );
1214    }
1215
1216    #[test]
1217    fn same_bytes_are_stored_once() {
1218        let (dir, s) = store();
1219        let a = png(dir.path(), "a.png", 10);
1220        let b = dir.path().join("copy-of-a.png");
1221        std::fs::copy(&a, &b).unwrap();
1222        let (id1, _) = ingest(&s, &a).unwrap();
1223        let (id2, _) = ingest(&s, &b).unwrap();
1224        assert_eq!(id1, id2);
1225        assert_eq!(walk_files(&s.root().join("blobs")).unwrap().len(), 1);
1226    }
1227
1228    #[test]
1229    fn text_file_is_stored_with_a_preview() {
1230        let (dir, s) = store();
1231        let src = dir.path().join("notes.txt");
1232        std::fs::write(&src, "hello").unwrap();
1233        let (tmp, id, _) = s.copy_in(&src, |_| true).unwrap();
1234        let meta = s.commit_named(&tmp, &id, "notes.txt", 2000).unwrap();
1235        assert_eq!(meta.kind, "text");
1236        assert!(!meta.is_image());
1237        let (thumb, _) = s.file(&id, &fingerprint(2000), Kind::Thumb).unwrap();
1238        assert_eq!(std::fs::read_to_string(thumb).unwrap(), "hello");
1239        let (send, _) = s.file(&id, &fingerprint(2000), Kind::Send).unwrap();
1240        assert_eq!(std::fs::read_to_string(send).unwrap(), "hello");
1241    }
1242
1243    #[test]
1244    fn cancelled_copy_leaves_nothing_behind() {
1245        let (dir, s) = store();
1246        let src = png(dir.path(), "a.png", 10);
1247        assert!(s.copy_in(&src, |_| false).is_err());
1248        assert!(walk_files(&s.root()).unwrap().is_empty());
1249    }
1250
1251    #[test]
1252    fn a_failed_decode_is_discarded_but_a_processed_one_is_kept() {
1253        let (dir, s) = store();
1254        let bad = png(dir.path(), "bad.png", 1);
1255        let bytes = std::fs::read(&bad).unwrap();
1256        std::fs::write(&bad, &bytes[..bytes.len() / 3]).unwrap();
1257        let (tmp, id, _) = s.copy_in(&bad, |_| true).unwrap();
1258        let (blob, kind) = s.place(&tmp, &id, "bad.png").unwrap();
1259        assert!(s
1260            .derive_and_save(&id, &blob, kind, "bad.png", 2000)
1261            .is_err());
1262        s.discard_if_unprocessed(&id);
1263        assert!(walk_files(&s.root().join("blobs")).unwrap().is_empty());
1264
1265        let (good, _) = ingest(&s, &png(dir.path(), "good.png", 2)).unwrap();
1266        s.discard_if_unprocessed(&good);
1267        assert!(s.meta(&good, &fingerprint(2000)).is_some());
1268    }
1269
1270    /// A jekt that wasn't delivered gives back what it was charged, never
1271    /// below zero (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §6.4).
1272    #[test]
1273    fn session_inline_bytes_can_be_refunded() {
1274        let (_dir, s) = store();
1275        s.add_session_inline_bytes("sess-r", 1500);
1276        s.refund_session_inline_bytes("sess-r", 1000);
1277        assert_eq!(s.session_inline_bytes("sess-r"), 500);
1278        s.refund_session_inline_bytes("sess-r", 9999);
1279        assert_eq!(s.session_inline_bytes("sess-r"), 0);
1280        s.refund_session_inline_bytes("sess-none", 10);
1281        assert_eq!(s.session_inline_bytes("sess-none"), 0);
1282    }
1283
1284    #[test]
1285    fn session_inline_bytes_accumulate_and_persist() {
1286        let (_dir, s) = store();
1287        assert_eq!(s.session_inline_bytes("sess-1"), 0);
1288        s.add_session_inline_bytes("sess-1", 1000);
1289        s.add_session_inline_bytes("sess-1", 500);
1290        assert_eq!(s.session_inline_bytes("sess-1"), 1500);
1291        assert_eq!(s.session_inline_bytes("sess-2"), 0);
1292        // A fresh Store over the same root sees it (a restart).
1293        let again = Store::new(s.root().to_path_buf());
1294        assert_eq!(again.session_inline_bytes("sess-1"), 1500);
1295        // A first turn counted before the session had an id carries over.
1296        s.add_session_inline_bytes("block:b1:new", 700);
1297        s.adopt_session_inline_bytes("block:b1:new", "sess-1");
1298        assert_eq!(s.session_inline_bytes("sess-1"), 2200);
1299        assert_eq!(
1300            s.session_inline_bytes("block:b1:new"),
1301            0,
1302            "moved, not copied"
1303        );
1304        s.adopt_session_inline_bytes("block:b1:new", "sess-1");
1305        assert_eq!(
1306            s.session_inline_bytes("sess-1"),
1307            2200,
1308            "adopting twice adds nothing"
1309        );
1310        // Kept for the full retention window, not the 7-day unsent one.
1311        let then = SystemTime::now() - Duration::from_secs(8 * 24 * 3600);
1312        for p in walk_files(&s.root().join("sessions")).unwrap() {
1313            set_mtime(&p, then).unwrap();
1314        }
1315        assert_eq!(s.sweep(Duration::from_secs(30 * 24 * 3600)), 0);
1316        assert_eq!(s.session_inline_bytes("sess-1"), 2200);
1317    }
1318
1319    fn age_all(s: &Store, id: &str, days: u64) {
1320        let then = SystemTime::now() - Duration::from_secs(days * 24 * 3600);
1321        for p in walk_files(s.root()).unwrap() {
1322            if p.to_string_lossy().contains(id) {
1323                set_mtime(&p, then).unwrap();
1324            }
1325        }
1326    }
1327
1328    #[test]
1329    fn never_sent_attachments_go_after_seven_days_sent_ones_after_retention() {
1330        let (dir, s) = store();
1331        let (draft, _) = ingest(&s, &png(dir.path(), "draft.png", 1)).unwrap();
1332        let (sent, _) = ingest(&s, &png(dir.path(), "sent.png", 2)).unwrap();
1333        s.mark_sent(&sent);
1334        age_all(&s, &draft, 8);
1335        age_all(&s, &sent, 8);
1336        let thirty = Duration::from_secs(30 * 24 * 3600);
1337        assert_eq!(s.sweep(thirty), 4, "the draft's four files go");
1338        let fp = fingerprint(2000);
1339        assert!(s.meta(&draft, &fp).is_none());
1340        assert!(
1341            s.meta(&sent, &fp).is_some(),
1342            "a sent attachment keeps the full window"
1343        );
1344        age_all(&s, &sent, 31);
1345        assert_eq!(s.sweep(thirty), 5, "four files plus the sent marker");
1346        assert!(s.meta(&sent, &fp).is_none());
1347    }
1348
1349    #[test]
1350    fn sweep_removes_stale_files_and_keeps_recent_ones() {
1351        let (dir, s) = store();
1352        let (old_id, _) = ingest(&s, &png(dir.path(), "old.png", 1)).unwrap();
1353        let (new_id, _) = ingest(&s, &png(dir.path(), "new.png", 2)).unwrap();
1354        let long_ago = SystemTime::now() - Duration::from_secs(40 * 24 * 3600);
1355        for p in walk_files(&s.root()).unwrap() {
1356            if p.to_string_lossy().contains(&old_id) {
1357                set_mtime(&p, long_ago).unwrap();
1358            }
1359        }
1360        let removed = s.sweep(Duration::from_secs(30 * 24 * 3600));
1361        assert_eq!(removed, 4);
1362        let fp = fingerprint(2000);
1363        assert!(s.meta(&old_id, &fp).is_none());
1364        assert!(s.meta(&new_id, &fp).is_some());
1365    }
1366
1367    /// A file sent with a message held for an agent that can't work is delivered with it up to a day
1368    /// later, so a short retention setting never takes it before then.
1369    #[test]
1370    fn a_short_retention_never_sweeps_a_file_a_hold_could_still_need() {
1371        let (dir, s) = store();
1372        let (id, _) = ingest(&s, &png(dir.path(), "held.png", 1)).unwrap();
1373        s.mark_sent(&id);
1374        let aged = |hours: u64| {
1375            let then = SystemTime::now() - Duration::from_secs(hours * 3600);
1376            for p in walk_files(s.root()).unwrap() {
1377                if p.to_string_lossy().contains(&id) {
1378                    set_mtime(&p, then).unwrap();
1379                }
1380            }
1381        };
1382        let minute = Duration::from_secs(60);
1383        aged(23);
1384        assert_eq!(s.sweep(minute), 0, "23 h old: a held message could still be waiting for it");
1385        assert!(s.meta(&id, &fingerprint(2000)).is_some());
1386        aged(26);
1387        assert_eq!(s.sweep(minute), 5, "past the hold and its margin, the setting applies: four files and the sent marker");
1388        assert!(s.meta(&id, &fingerprint(2000)).is_none());
1389    }
1390
1391    #[test]
1392    fn touch_rescues_an_attachment_from_the_sweep() {
1393        let (dir, s) = store();
1394        let (id, _) = ingest(&s, &png(dir.path(), "a.png", 1)).unwrap();
1395        let long_ago = SystemTime::now() - Duration::from_secs(40 * 24 * 3600);
1396        for p in walk_files(&s.root()).unwrap() {
1397            set_mtime(&p, long_ago).unwrap();
1398        }
1399        s.touch(&id, &fingerprint(2000));
1400        assert_eq!(s.sweep(Duration::from_secs(30 * 24 * 3600)), 0);
1401        assert!(s.meta(&id, &fingerprint(2000)).is_some());
1402    }
1403
1404    #[test]
1405    fn changing_the_send_edge_rederives_from_the_stored_original() {
1406        let (dir, s) = store();
1407        let p = dir.path().join("wide.png");
1408        DynamicImage::ImageRgb8(RgbImage::from_pixel(1200, 600, Rgb([5, 5, 5])))
1409            .save_with_format(&p, ImageFormat::Png)
1410            .unwrap();
1411        let (id, first) = ingest(&s, &p).unwrap();
1412        assert_eq!(first.send_width, 1200);
1413        assert!(s.meta(&id, &fingerprint(800)).is_none());
1414        let again = s.ensure_derived(&id, 800).unwrap();
1415        assert_eq!((again.send_width, again.send_height), (800, 400));
1416        // The original fingerprint is untouched.
1417        assert_eq!(s.meta(&id, &fingerprint(2000)).unwrap().send_width, 1200);
1418    }
1419
1420    fn derived_file(s: &Store, id: &str, name: &str) -> PathBuf {
1421        let dir = s.root().join("derived").join(&id[..2]);
1422        std::fs::create_dir_all(&dir).unwrap();
1423        let p = dir.join(format!("{id}.{name}"));
1424        std::fs::write(&p, b"x").unwrap();
1425        p
1426    }
1427
1428    #[test]
1429    fn a_message_that_names_the_text_version_names_its_attachment() {
1430        let (a, b) = ("a".repeat(64), "b".repeat(64));
1431        let note = format!("1. report.pdf [PDF, 2 pages; text version: /home/u/.agentmux/data/attachments/derived/aa/{a}.v1-e1568.text.txt]\n2. memo.docx [text version: C:\\\\Users\\\\u\\\\attachments\\\\derived\\\\bb\\\\{b}.v1-e1568.text.txt] again /derived/aa/{a}.v1-e1568.text.txt");
1432        assert_eq!(text_cache_ids(&note), vec![a, b]);
1433        assert!(text_cache_ids("a plain message with no attachment").is_empty());
1434        let near = format!("derived/aa/{}.v1.thumb.png and derived/aa/{}.v1.json", "a".repeat(64), "a".repeat(64));
1435        assert!(text_cache_ids(&near).is_empty(), "only a text version is a text cache");
1436    }
1437
1438    #[test]
1439    fn removing_the_text_cache_leaves_the_original_and_the_rest_and_the_next_send_extracts_again() {
1440        let (_dir, s) = store();
1441        let (a, b) = ("a".repeat(64), "b".repeat(64));
1442        let (text, text_old, thumb, meta, sent) = (
1443            derived_file(&s, &a, "v1-e1568.text.txt"),
1444            derived_file(&s, &a, "v1-e1024.text.md"),
1445            derived_file(&s, &a, "v1-e1568.thumb.png"),
1446            derived_file(&s, &a, "v1-e1568.json"),
1447            derived_file(&s, &a, "sent"),
1448        );
1449        let other = derived_file(&s, &b, "v1-e1568.text.txt");
1450        let blob = s.blob_path(&a, "pdf");
1451        std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
1452        std::fs::write(&blob, b"%PDF").unwrap();
1453        assert_eq!(s.remove_text_caches(&[a.clone(), "../../etc/passwd".to_string(), "short".to_string()]), 2);
1454        assert!(!text.exists() && !text_old.exists());
1455        assert!(thumb.exists() && meta.exists() && sent.exists() && blob.exists(), "only the text goes");
1456        assert!(other.exists(), "another attachment's text stays");
1457        assert_eq!(s.remove_text_caches(&[a]), 0, "a second removal finds nothing");
1458    }
1459}