Skip to main content

lean_ctx/core/archive/
recovery.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Recovery copies bound to a [`Lineage`] (G02).
3//!
4//! A text that is compressed or cut down on its way to the model keeps a
5//! recovery copy of the original only if the original's lineage is known,
6//! and the copy is handed back only under the authority that holds at that
7//! moment. The copy lives in the archive store, with its bounds and cleanup:
8//!
9//! - a lineage of project files only is the existing source-bound archive
10//!   entry (`store_with_authority` / `retrieve_checked`), with the same id —
11//!   so the pipeline's archive copy of a tool result and a recovery copy of
12//!   the same text and sources are one entry;
13//! - any other lineage (caller-supplied sources, or files and such sources)
14//!   is an entry that carries the lineage itself and no file authority. Every
15//!   other read path refuses such an entry; only
16//!   [`retrieve_recovery_checked`] serves it.
17//!
18//! Ids are content-addressed and deterministic (#498): the same text under
19//! the same lineage always has the same id. The policy a caller-supplied
20//! source was admitted under is part of that identity, so a copy stored
21//! under one policy is never served under another.
22
23use super::delivered::{self, Lineage, LineageRefusal};
24
25/// Address of a recovery copy: 64 lowercase hex characters.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct RecoveryId(String);
28
29impl RecoveryId {
30    /// `None` for anything that is not a canonical id: an untrusted handle
31    /// never supplies path components.
32    #[must_use]
33    pub fn parse(id: &str) -> Option<Self> {
34        (id.len() == 64
35            && id
36                .bytes()
37                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()))
38        .then(|| Self(id.to_owned()))
39    }
40
41    #[must_use]
42    pub fn as_str(&self) -> &str {
43        &self.0
44    }
45}
46
47/// Why no recovery copy is stored or returned. Content-free.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum RecoveryRefusal {
50    /// No lineage, an incomplete one, or an entry without one.
51    UnknownLineage,
52    /// A caller-supplied source has no current presentation.
53    SourceNotPresented,
54    /// A source is refused under the current rights or policy, or the stored
55    /// text is withheld by the current content rules.
56    SourceNoLongerAdmitted,
57    /// The text may not enter a store (restricted, withheld or rewritten by
58    /// the current rules, larger than the archive bound, archive disabled).
59    NotStorable,
60    /// No such copy (never stored, evicted, or not intact).
61    Missing,
62}
63
64impl From<LineageRefusal> for RecoveryRefusal {
65    fn from(refusal: LineageRefusal) -> Self {
66        match refusal {
67            LineageRefusal::Unknown => Self::UnknownLineage,
68            LineageRefusal::SourceNotPresented => Self::SourceNotPresented,
69            LineageRefusal::SourceNoLongerAdmitted => Self::SourceNoLongerAdmitted,
70        }
71    }
72}
73
74impl std::fmt::Display for RecoveryRefusal {
75    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        formatter.write_str(match self {
77            Self::UnknownLineage => "recovery.unknown_lineage",
78            Self::SourceNotPresented => "recovery.source_not_presented",
79            Self::SourceNoLongerAdmitted => "recovery.source_no_longer_admitted",
80            Self::NotStorable => "recovery.not_storable",
81            Self::Missing => "recovery.missing",
82        })
83    }
84}
85
86/// Whether exactly `original` — not a rewritten form of it — may enter a
87/// store under the current project and gateway rules (E3: restricted or
88/// withheld text never does). A recovery copy that differs from the original
89/// would not be a recovery of it.
90fn storable_exactly(original: &str) -> bool {
91    !original.is_empty()
92        && original.len() <= super::MAX_ARCHIVE_SIZE
93        && crate::core::policy::content::protect_active(original)
94            .is_ok_and(|protected| &*protected == original)
95        && crate::core::context_admission::recovery::admit_for_storage(original)
96            .is_some_and(|admitted| admitted == original)
97}
98
99fn lineage_id(lineage: &Lineage, content: &str) -> Option<String> {
100    let mut hash = blake3::Hasher::new();
101    hash.update(b"leanctx-lineage-archive-v1\0");
102    hash.update(lineage.identity_digest()?.as_bytes());
103    hash.update(b"\0");
104    hash.update(content.as_bytes());
105    Some(hash.finalize().to_hex().to_string())
106}
107
108/// Stores a recovery copy of `original` bound to `lineage`. Call inside the
109/// request's `REQUEST_PROJECT` scope. Stores nothing unless the lineage is
110/// complete, every source holds now ([`Lineage::still_admitted`], which for a
111/// file source includes "storable") and the text itself may enter a store
112/// unchanged. Storing the same text under the same lineage again returns the
113/// same id.
114pub fn store_recovery_with_lineage(
115    original: &str,
116    lineage: &Lineage,
117) -> Result<RecoveryId, RecoveryRefusal> {
118    lineage.still_admitted()?;
119    let storable = crate::core::policy::runtime::with_source_view(|| storable_exactly(original))
120        .unwrap_or(false);
121    if !storable || !super::is_enabled() {
122        return Err(RecoveryRefusal::NotStorable);
123    }
124    if let Some(files) = lineage.files_only() {
125        return super::store_with_authority(
126            "recovery",
127            "recovery-copy",
128            original,
129            None,
130            Some(files),
131        )
132        .filter(|stored| !stored.truncated)
133        .and_then(|stored| RecoveryId::parse(&stored.id))
134        .inspect(issued)
135        .ok_or(RecoveryRefusal::NotStorable);
136    }
137    let id = lineage_id(lineage, original).ok_or(RecoveryRefusal::UnknownLineage)?;
138    let stored = super::with_archive_lock(|| {
139        let content_path = super::content_path(&id);
140        if content_path.exists() && super::meta_path(&id).exists() {
141            return Some(());
142        }
143        std::fs::create_dir_all(super::entry_dir(&id)).ok()?;
144        if !content_path.exists() {
145            crate::core::atomic_fs::try_atomic_write(&content_path, original.as_bytes(), None)
146                .ok()?;
147            #[cfg(unix)]
148            super::set_private_file_perms(&content_path);
149        }
150        // No FTS row and no by-content pointer: the copy is reachable by its
151        // id only, through `retrieve_recovery_checked`.
152        let mut entry = super::new_entry(
153            &id,
154            "recovery",
155            "recovery-copy",
156            original,
157            None,
158            lean_ctx_time::UtcDateTime::now(),
159        );
160        // With the content-free reference of the presenter this copy was
161        // first stored for (a digest of a verifier; authorizes nothing).
162        entry.lineage = Some(lineage.recorded_for_presenter());
163        if super::write_metadata(&entry).is_none() {
164            let _ = std::fs::remove_file(content_path);
165            return None;
166        }
167        Some(())
168    })
169    .flatten();
170    match stored {
171        Some(()) => RecoveryId::parse(&id)
172            .inspect(issued)
173            .ok_or(RecoveryRefusal::NotStorable),
174        None => Err(RecoveryRefusal::NotStorable),
175    }
176}
177
178/// G08: a recovery copy is stored under `id` — from here on a reference a
179/// host can pass back. The receipt trace of a delivery whose bytes carry it
180/// lists it (`receipt_store::references`): the id, never the copy.
181fn issued(id: &RecoveryId) {
182    crate::core::context_admission::receipt_store::references::note_recovery(id.as_str());
183}
184
185/// Resolves a recovery copy under CURRENT authority only. Call inside the
186/// `REQUEST_PROJECT` scope of the request that asks for it. The lineage
187/// stored with the copy must hold now; the stored text must still pass the
188/// current content rules unchanged. The released text is registered as
189/// delivered under that lineage.
190pub fn retrieve_recovery_checked(id: &RecoveryId) -> Result<String, RecoveryRefusal> {
191    let entry = super::read_entry(id.as_str()).ok_or(RecoveryRefusal::Missing)?;
192    let Some(lineage) = entry.lineage else {
193        // A file-bound copy: the archive's own checked read, which re-admits
194        // every source itself (one pass, the same check as ever) and records
195        // the released text as delivered.
196        if entry.authority.is_none() {
197            return Err(RecoveryRefusal::UnknownLineage);
198        }
199        return super::retrieve_checked(id.as_str()).map_err(|error| match error {
200            super::ArchiveResolveError::Refused(_) => RecoveryRefusal::SourceNoLongerAdmitted,
201            super::ArchiveResolveError::Missing | super::ArchiveResolveError::Malformed => {
202                RecoveryRefusal::Missing
203            }
204        });
205    };
206    lineage.still_admitted()?;
207    let content = crate::core::atomic_fs::read_store_file(
208        &super::archive_base_dir(),
209        &super::content_path(id.as_str()),
210    )
211    .map_err(|_| RecoveryRefusal::Missing)?;
212    if content.len() > super::MAX_ARCHIVE_SIZE
213        || lineage_id(&lineage, &content).as_deref() != Some(id.as_str())
214    {
215        // Not the text that was stored under this lineage.
216        return Err(RecoveryRefusal::Missing);
217    }
218    // Project policy first, then the gateway's own decision on the stored
219    // text — both with the equality rule, both under current rules.
220    let released = crate::core::policy::runtime::with_source_view(|| {
221        crate::core::policy::content::protect_active(&content)
222            .is_ok_and(|protected| *protected == content)
223            && readmitted(id, &content)
224    })
225    .unwrap_or(false);
226    if !released {
227        return Err(RecoveryRefusal::SourceNoLongerAdmitted);
228    }
229    delivered::record_lineage(&delivered::digest(&content), &lineage);
230    Ok(content)
231}
232
233/// G08: the copy is admitted again in the call that asks for it. A lineage
234/// that still holds says its SOURCES are still admitted; whether the stored
235/// TEXT passes the Context Gateway's current rules is decided here, recorded
236/// in the call's open capture and named by the recovery id — so the receipt
237/// of the call carries that decision instead of none.
238///
239/// In every mode. The copy is bound to its id by its content, so a change
240/// the gateway would make is unrepresentable: a text it would mask or
241/// withhold is not released, and the bound admission records that as a
242/// refusal (`source.bytes_not_preserved`), never as a redaction.
243fn readmitted(id: &RecoveryId, content: &str) -> bool {
244    let unchanged = crate::core::context_admission::admit_bound_context_source(
245        content,
246        &crate::core::context_admission::origin::SourceClass::Unclassified { tool: "recovery" },
247    )
248    .is_ok();
249    if unchanged {
250        let reference = format!("recovery:{}", id.as_str());
251        crate::core::context_admission::capture::note_source_id(&reference);
252    }
253    unchanged
254}
255
256/// The lineage stored with a recovery copy, read without resolving the copy:
257/// nothing is checked, released or recorded. For a caller that must decide
258/// whether the copy is its request's BEFORE the text is read.
259#[must_use]
260pub fn recovery_lineage(id: &RecoveryId) -> Option<Lineage> {
261    super::read_entry(id.as_str())?.lineage
262}
263
264#[cfg(test)]
265mod tests {
266    use std::path::{Path, PathBuf};
267
268    use super::*;
269    use crate::core::archive::authority::ArchiveAuthority;
270    use crate::core::archive::presented::{PresentedBinding, record_presentation};
271    use crate::core::policy::runtime::{REQUEST_PROJECT, TestPolicyOverride};
272
273    const GOVERNED: &str = "[context_gateway]\nmode = \"governed\"\nclassification = \"warn\"\n";
274    const ORIGINAL: &str = "pub fn kept() {}\n";
275
276    fn isolated(config: &str) -> crate::core::data_dir::IsolatedDataDir {
277        let data = crate::core::data_dir::isolated_data_dir();
278        let dir = crate::core::paths::config_dir_read_only().expect("isolated config dir");
279        std::fs::create_dir_all(&dir).expect("config dir");
280        std::fs::write(dir.join("config.toml"), config).expect("config");
281        data
282    }
283
284    fn project() -> (tempfile::TempDir, PathBuf) {
285        let directory = tempfile::tempdir().expect("project");
286        let root = directory.path().canonicalize().expect("canonical root");
287        (directory, root)
288    }
289
290    fn scoped<T>(root: &Path, operation: impl FnOnce() -> T) -> T {
291        REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(root.to_path_buf())), operation)
292    }
293
294    fn file_lineage(root: &Path, name: &str, content: &str) -> Lineage {
295        let path = root.join(name);
296        std::fs::write(&path, content).expect("source");
297        let admitted = crate::core::rooted_read::read_file_for_tool_rooted(
298            path.to_str().expect("utf-8 path"),
299            root.to_str().expect("utf-8 root"),
300            "ctx_read",
301        )
302        .expect("admitted read");
303        Lineage::of_files(
304            ArchiveAuthority::file(
305                root,
306                path.to_str().expect("utf-8 path"),
307                "ctx_read",
308                &admitted,
309            )
310            .expect("protection is active: the read is bound"),
311        )
312    }
313
314    fn stored_files(data: &crate::core::data_dir::IsolatedDataDir) -> usize {
315        fn count(directory: &Path) -> usize {
316            std::fs::read_dir(directory).map_or(0, |entries| {
317                entries
318                    .flatten()
319                    .map(|entry| {
320                        let path = entry.path();
321                        if path.is_dir() {
322                            count(&path)
323                        } else {
324                            usize::from(path.extension().is_some_and(|ext| ext == "txt"))
325                        }
326                    })
327                    .sum()
328            })
329        }
330        count(&data.path().join("archives"))
331    }
332
333    /// File lineage: stored, resolved, deterministic id, the archive's own
334    /// entry. Source deleted: refused, nothing returned. Before, a recovery
335    /// copy existed under protection only if a tool call had archived exactly
336    /// this text.
337    #[test]
338    fn a_file_bound_recovery_copy_resolves_only_while_its_source_holds() {
339        let _data = isolated(GOVERNED);
340        let _community = TestPolicyOverride::set(None);
341        let (_directory, root) = project();
342        scoped(&root, || {
343            let lineage = file_lineage(&root, "kept.rs", ORIGINAL);
344            let id = store_recovery_with_lineage(ORIGINAL, &lineage).expect("stored");
345            assert_eq!(
346                store_recovery_with_lineage(ORIGINAL, &lineage).as_ref(),
347                Ok(&id),
348                "identical input, identical id"
349            );
350            assert_eq!(retrieve_recovery_checked(&id).as_deref(), Ok(ORIGINAL));
351            assert_eq!(
352                crate::core::archive::retrieve_checked(id.as_str()).as_deref(),
353                Ok(ORIGINAL),
354                "one entry for the archive and the recovery path"
355            );
356
357            // A text derived from the original keeps the original's lineage
358            // and fails together with it.
359            let stub = format!("[compressed; recover with {}]", id.as_str());
360            let known = delivered::lineage_of(&delivered::digest(ORIGINAL)).expect("on record");
361            assert!(delivered::record_derived(&delivered::digest(&stub), &known));
362            assert_eq!(
363                delivered::lineage_of(&delivered::digest(&stub)),
364                Some(known)
365            );
366
367            std::fs::remove_file(root.join("kept.rs")).expect("delete the source");
368            assert_eq!(
369                retrieve_recovery_checked(&id),
370                Err(RecoveryRefusal::SourceNoLongerAdmitted)
371            );
372            assert_eq!(
373                delivered::lineage_of(&delivered::digest(&stub))
374                    .expect("still on record")
375                    .still_admitted(),
376                Err(LineageRefusal::SourceNoLongerAdmitted)
377            );
378            assert_eq!(
379                store_recovery_with_lineage(ORIGINAL, &lineage),
380                Err(RecoveryRefusal::SourceNoLongerAdmitted)
381            );
382        });
383    }
384
385    /// Nothing reaches the disk for an unknown lineage or a restricted
386    /// source, and a malformed or unknown id resolves to nothing.
387    #[test]
388    fn unknown_or_restricted_lineage_stores_nothing() {
389        let data = isolated(GOVERNED);
390        let _community = TestPolicyOverride::set(None);
391        let (_directory, root) = project();
392        scoped(&root, || {
393            assert_eq!(
394                store_recovery_with_lineage(ORIGINAL, &Lineage::of_presented(Vec::new())),
395                Err(RecoveryRefusal::UnknownLineage)
396            );
397
398            // Delivered under `classification = "warn"`, but restricted: the
399            // source is not storable (E3).
400            let marked = "*** TOP SECRET ***\nlaunch window\n";
401            let restricted = file_lineage(&root, "plan.md", marked);
402            assert!(matches!(
403                store_recovery_with_lineage("launch window\n", &restricted),
404                Err(RecoveryRefusal::SourceNoLongerAdmitted | RecoveryRefusal::NotStorable)
405            ));
406            // A clean source does not make restricted TEXT storable.
407            let clean = file_lineage(&root, "kept.rs", ORIGINAL);
408            assert_eq!(
409                store_recovery_with_lineage(marked, &clean),
410                Err(RecoveryRefusal::NotStorable)
411            );
412            assert_eq!(stored_files(&data), 0, "nothing on disk");
413
414            assert!(RecoveryId::parse("../../etc/passwd").is_none());
415            let absent = RecoveryId::parse(&"0".repeat(64)).expect("canonical id");
416            assert_eq!(
417                retrieve_recovery_checked(&absent),
418                Err(RecoveryRefusal::Missing)
419            );
420        });
421        // No request project: no lineage can be verified.
422        let lineage = scoped(&root, || file_lineage(&root, "kept.rs", ORIGINAL));
423        assert!(store_recovery_with_lineage(ORIGINAL, &lineage).is_err());
424        assert_eq!(stored_files(&data), 0);
425    }
426
427    /// Caller-supplied sources: stored and resolved only while a current
428    /// presentation exists; the copy is not reachable through the ordinary
429    /// archive read; a copy stored under one policy is never served under
430    /// another, whatever is presented afterwards.
431    #[test]
432    fn a_presented_recovery_copy_needs_a_current_presentation() {
433        let data = isolated("");
434        let _community = TestPolicyOverride::set(None);
435        let (_directory, root) = project();
436        let prepared = "## leanctx-source-v1\ninvoice ledger\n";
437        scoped(&root, || {
438            let binding =
439                PresentedBinding::admitted_now(&root, "ref-quartz", "source-one", "sha256:aa")
440                    .expect("policy identity available");
441            let lineage = Lineage::of_presented(vec![binding.clone()]);
442            assert_eq!(
443                store_recovery_with_lineage(prepared, &lineage),
444                Err(RecoveryRefusal::SourceNotPresented),
445                "bound, but never presented"
446            );
447            assert_eq!(stored_files(&data), 0);
448
449            assert!(record_presentation(&binding));
450            let id = store_recovery_with_lineage(prepared, &lineage).expect("stored");
451            assert_eq!(
452                store_recovery_with_lineage(prepared, &lineage).as_ref(),
453                Ok(&id)
454            );
455            assert_eq!(retrieve_recovery_checked(&id).as_deref(), Ok(prepared));
456            assert!(
457                crate::core::archive::retrieve_checked(id.as_str()).is_err(),
458                "the ordinary archive read never serves a lineage-bound copy"
459            );
460            assert!(
461                crate::core::archive::list_entries(None)
462                    .iter()
463                    .all(|entry| entry.id != id.as_str()),
464                "and does not list it"
465            );
466
467            // The presentation lapses (what an elapsed validity leaves).
468            let presented = data
469                .path()
470                .join("archives")
471                .join(crate::core::archive::presented::REGISTER_DIRECTORY);
472            std::fs::remove_dir_all(&presented).expect("presentation register");
473            assert_eq!(
474                retrieve_recovery_checked(&id),
475                Err(RecoveryRefusal::SourceNotPresented)
476            );
477            // Presented again under the same policy: readable again.
478            assert!(record_presentation(&binding));
479            assert_eq!(retrieve_recovery_checked(&id).as_deref(), Ok(prepared));
480
481            // The policy changes: this copy is never served again, also not
482            // after a new presentation under the new policy.
483            let dir = crate::core::paths::config_dir_read_only().expect("config dir");
484            std::fs::write(
485                dir.join("config.toml"),
486                "[context_gateway]\nmode = \"governed\"\n",
487            )
488            .expect("config");
489            assert_eq!(
490                retrieve_recovery_checked(&id),
491                Err(RecoveryRefusal::SourceNoLongerAdmitted)
492            );
493            let renewed =
494                PresentedBinding::admitted_now(&root, "ref-quartz", "source-one", "sha256:aa")
495                    .expect("policy identity available");
496            assert!(record_presentation(&renewed));
497            assert_eq!(
498                retrieve_recovery_checked(&id),
499                Err(RecoveryRefusal::SourceNoLongerAdmitted)
500            );
501            // The same text under the new policy is another copy, another id.
502            let renewed_id =
503                store_recovery_with_lineage(prepared, &Lineage::of_presented(vec![renewed]))
504                    .expect("stored under the current policy");
505            assert_ne!(renewed_id, id);
506            assert_eq!(
507                retrieve_recovery_checked(&renewed_id).as_deref(),
508                Ok(prepared)
509            );
510        });
511    }
512
513    /// G08: under protection the call that expands a presented copy admits
514    /// its text again — the decision is in that call's capture, named by the
515    /// recovery id — and a text the gateway would mask is never handed out,
516    /// whether the store took it or not.
517    #[test]
518    fn a_presented_copy_is_readmitted_in_the_call_that_expands_it() {
519        use crate::core::context_admission::capture::{
520            ADMISSIONS, AdmissionCapture, CallSnapshot, SourceName,
521        };
522        let _data = isolated(GOVERNED);
523        let _community = TestPolicyOverride::set(None);
524        let (_directory, root) = project();
525        let prepared = "## leanctx-source-v1\ninvoice ledger\n";
526        scoped(&root, || {
527            let binding =
528                PresentedBinding::admitted_now(&root, "ref-quartz", "source-one", "sha256:aa")
529                    .expect("policy identity available");
530            assert!(record_presentation(&binding));
531            let lineage = Lineage::of_presented(vec![binding]);
532            let id = store_recovery_with_lineage(prepared, &lineage).expect("stored");
533            let capture = AdmissionCapture::for_call(CallSnapshot::take());
534            let expanded =
535                ADMISSIONS.sync_scope(Some(capture.clone()), || retrieve_recovery_checked(&id));
536            assert_eq!(expanded.as_deref(), Ok(prepared));
537            let (named, _) = capture.source_references();
538            assert_eq!(named.len(), 1, "the expansion's own decision");
539            assert_eq!(
540                named[0].1,
541                SourceName::Id(format!("recovery:{}", id.as_str()))
542            );
543
544            let masked = "## leanctx-source-v1\npaid with card 4111 1111 1111 1111\n";
545            match store_recovery_with_lineage(masked, &lineage) {
546                Ok(id) => assert_eq!(
547                    retrieve_recovery_checked(&id),
548                    Err(RecoveryRefusal::SourceNoLongerAdmitted)
549                ),
550                Err(refusal) => assert!(matches!(
551                    refusal,
552                    RecoveryRefusal::NotStorable | RecoveryRefusal::SourceNoLongerAdmitted
553                )),
554            }
555        });
556    }
557}