Skip to main content

lean_ctx/core/archive/
bindings.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Source bindings of stored items whose own record has no place for one:
3//! knowledge facts and session findings.
4//!
5//! The binding is kept beside the store, in a register of the archive's one
6//! persistence form (`archive::register`: owner-only shards, replaced
7//! atomically under a bounded lock, bounded in entries and age), keyed by the
8//! item's identity. The store's own format is unchanged; an item written
9//! before bindings existed, an item whose binding was evicted or has expired,
10//! and an item whose text no longer is the bound text are all the same thing:
11//! originless.
12//!
13//! A binding is written only from sources that exist AT THE WRITE: files the
14//! writer named and the admitted reader returned then ([`sources_at`]), or the
15//! complete source set of the very call that produced the item
16//! (`sources_of_call`). Nothing is inferred later. Owner decision E3: a
17//! restricted source or text binds nothing.
18
19use super::authority::ArchiveAuthority;
20use super::register::{self, Register};
21use crate::core::context_admission::carrier::Withheld;
22use crate::core::context_admission::stored::{self, Lineage, SourceRef, StoredBinding};
23
24const REGISTER: Register = Register {
25    name: "bindings",
26    shard_entries: 128,
27    max_age_seconds: 180 * 24 * 60 * 60,
28};
29
30/// The identity of a stored item.
31#[derive(Debug, Clone, Copy)]
32pub enum Item<'a> {
33    /// A knowledge fact: project root as its store names it, category, key.
34    KnowledgeFact {
35        project: &'a str,
36        category: &'a str,
37        key: &'a str,
38    },
39    /// A session finding: session id and the file it was recorded for.
40    SessionFinding {
41        session: &'a str,
42        file: Option<&'a str>,
43    },
44}
45
46impl Item<'_> {
47    fn origin(&self) -> &'static str {
48        match self {
49            Self::KnowledgeFact { .. } => "knowledge:fact",
50            Self::SessionFinding { .. } => "session:finding",
51        }
52    }
53
54    /// Register key. A finding has no key of its own, so its text is part of
55    /// its identity; a fact keeps its key when its value is replaced, and the
56    /// binding's content digest then tells the old value from the new one.
57    fn key(&self, text: &str) -> String {
58        let parts: [&str; 4] = match *self {
59            Self::KnowledgeFact {
60                project,
61                category,
62                key,
63            } => ["fact", project, category, key],
64            Self::SessionFinding { session, file } => {
65                ["finding", session, file.unwrap_or_default(), text]
66            }
67        };
68        let mut hash = blake3::Hasher::new();
69        hash.update(b"leanctx-item-binding-v1");
70        for part in parts {
71            hash.update(b"\0");
72            hash.update(&(part.len() as u64).to_le_bytes());
73            hash.update(part.as_bytes());
74        }
75        hash.finalize().to_hex().to_string()
76    }
77}
78
79/// The sources a writer names for an item, each read NOW through the admitted
80/// rooted reader for `tool`. A path relative to the project is resolved in
81/// it. `None` when no path is named or any of them cannot be bound (missing,
82/// outside the project, not permitted, restricted, only lossily readable):
83/// an item is bound to all the sources it names or to none.
84pub fn sources_at<S: AsRef<str>>(project: &str, paths: &[S], tool: &str) -> Option<Vec<SourceRef>> {
85    if paths.is_empty() {
86        return None;
87    }
88    paths
89        .iter()
90        .map(|path| {
91            let path = std::path::Path::new(project).join(path.as_ref());
92            SourceRef::read(path.to_str()?, project, tool)
93                .ok()
94                .map(|(_, source)| source)
95        })
96        .collect()
97}
98
99/// The one source `path` names in `project`, or why it cannot be bound
100/// (missing, outside the project, not permitted, restricted).
101pub fn source_at(project: &str, path: &str, tool: &str) -> Result<SourceRef, String> {
102    let joined = std::path::Path::new(project).join(path);
103    let Some(joined) = joined.to_str() else {
104        return Err("the path is not UTF-8".to_owned());
105    };
106    SourceRef::read(joined, project, tool)
107        .map(|(_, source)| source)
108        .map_err(|withheld| withheld.codes().join(", "))
109}
110
111/// The sources of an item that was derived from the output of the current
112/// call: the call's captured source set, which the caller passes only for a
113/// tool that declares every source. Each file is read again now and must
114/// deliver what the call was given. `None` for an incomplete set.
115pub(crate) fn sources_of_call(capture: &ArchiveAuthority) -> Option<Vec<SourceRef>> {
116    let project = capture.project();
117    capture
118        .sources()?
119        .into_iter()
120        .map(|(path, tool, admitted_digest)| {
121            SourceRef::read_as_admitted(path, project, tool, admitted_digest)
122        })
123        .collect()
124}
125
126/// Bind `text`, as its store keeps it, to `sources`. Returns whether the item
127/// is bound now. `false` — the item stays originless — when the text or a
128/// source is restricted or withheld, when admission would rewrite the text
129/// (the binding would be of another text), without a project under
130/// protection, or when the register refuses the write.
131pub fn bind(item: &Item<'_>, text: &str, project: &str, sources: Vec<SourceRef>) -> bool {
132    prepare(item, text, project, sources).is_some_and(|binding| write(item, text, binding))
133}
134
135/// The binding [`bind`] would write, not yet written. `None` for every case
136/// in which [`bind`] leaves the item originless before the register is asked.
137pub(crate) fn prepare(
138    item: &Item<'_>,
139    text: &str,
140    project: &str,
141    sources: Vec<SourceRef>,
142) -> Option<StoredBinding> {
143    if sources.is_empty() {
144        return None;
145    }
146    let lineage = Lineage::of(sources).ok()?;
147    let (admitted, binding) =
148        stored::admit_and_bind(text, item.origin(), Some(project), lineage).ok()?;
149    (admitted == text).then_some(binding)
150}
151
152fn write(item: &Item<'_>, text: &str, binding: StoredBinding) -> bool {
153    REGISTER.update::<StoredBinding>(&item.key(text), register::now(), |_| Some(binding))
154}
155
156/// A binding prepared for an item that is derived from bound items, to be
157/// written once the item's store has kept the text (`carry`).
158pub struct Carried(StoredBinding);
159
160impl Carried {
161    /// Write the binding for `item`, whose store keeps `text` now. `false`
162    /// when `text` is not the text the binding was prepared for or the
163    /// register refuses the write: the item is then NOT bound, and its store
164    /// must not keep a text that was derived from bound items.
165    pub fn commit(self, item: &Item<'_>, text: &str) -> bool {
166        self.0.binds(text) && write(item, text, self.0)
167    }
168}
169
170/// The sources a binding names, each read again now. `Err` when the bound
171/// item is not served now (`stored::serve_stored`) or a source no longer
172/// delivers what the binding was made from; `Ok(None)` for a binding that
173/// names no file (caller-supplied text, no project).
174fn held_sources(
175    binding: &StoredBinding,
176    text: &str,
177    reader_project: Option<&str>,
178) -> Result<Option<(String, Vec<SourceRef>)>, Withheld> {
179    stored::serve_stored(text, Some(binding), reader_project)?;
180    let Some((project, files)) = binding.file_sources() else {
181        return Ok(None);
182    };
183    let sources = files
184        .into_iter()
185        .map(|(path, tool, admitted_digest)| {
186            SourceRef::read_as_admitted(path, project, tool, admitted_digest)
187                .ok_or_else(Withheld::source_unavailable)
188        })
189        .collect::<Result<Vec<_>, _>>()?;
190    Ok(Some((project.to_owned(), sources)))
191}
192
193/// The binding of an item whose `text` a store DERIVES from other stored
194/// items (`origins`, each with the text its store keeps): a knowledge fact
195/// built from a session finding. The derived text is not the origin's text,
196/// so the origin's binding cannot be copied; the derived item is bound to the
197/// same files, read again now through the admitted reader, exactly as a
198/// writer that names them would bind it ([`sources_at`], [`bind`]).
199///
200/// - `Ok(Some(_))`: every origin has a register entry that holds now. The
201///   prepared binding names the joined sources; the caller stores the text
202///   and then calls [`Carried::commit`].
203/// - `Ok(None)`: an origin has no register entry (never bound, evicted,
204///   expired) or one that names no file. The derived item is originless, as
205///   its origin is; nothing is inferred from a path the origin mentions.
206/// - `Err`, while protection is active: an origin is bound and is not served
207///   now, a source no longer admits, the origins belong to different
208///   projects, or the derived text cannot be bound (restricted, rewritten by
209///   admission). The derived item must NOT be stored — it would be an unbound
210///   copy of text whose source is withheld.
211///
212/// Without protection nothing is refused: what cannot be carried is
213/// originless, as every item is in that mode.
214pub(crate) fn carry(
215    derived: &Item<'_>,
216    text: &str,
217    origins: &[(Item<'_>, &str)],
218    reader_project: Option<&str>,
219) -> Result<Option<Carried>, Withheld> {
220    let enforced = stored::source_authority_required();
221    let mut project: Option<String> = None;
222    let mut sources = Vec::new();
223    let mut bound = !origins.is_empty();
224    for (origin, origin_text) in origins {
225        let Some(binding) = binding_of(origin, origin_text) else {
226            bound = false;
227            continue;
228        };
229        let held = held_sources(&binding, origin_text, reader_project).and_then(|held| {
230            let foreign = held.as_ref().is_some_and(|(root, _)| {
231                project
232                    .as_deref()
233                    .is_some_and(|joined| joined != root.as_str())
234            });
235            if foreign {
236                Err(Withheld::no_source_authority())
237            } else {
238                Ok(held)
239            }
240        });
241        match held {
242            Ok(Some((root, files))) => {
243                project = Some(root);
244                sources.extend(files);
245            }
246            Err(withheld) if enforced => return Err(withheld),
247            Ok(None) | Err(_) => bound = false,
248        }
249    }
250    let Some(project) = project.filter(|_| bound) else {
251        return Ok(None);
252    };
253    carried(derived, text, &project, sources, enforced)
254}
255
256/// The last step of [`carry`] and [`carry_from`]: the binding of the derived
257/// `text` to the sources its origins hold. While protection is active a text
258/// that cannot be bound to them is refused, never stored unbound.
259fn carried(
260    derived: &Item<'_>,
261    text: &str,
262    project: &str,
263    sources: Vec<SourceRef>,
264    enforced: bool,
265) -> Result<Option<Carried>, Withheld> {
266    match prepare(derived, text, project, sources) {
267        Some(binding) => Ok(Some(Carried(binding))),
268        None if enforced => Err(Withheld::no_source_authority()),
269        None => Ok(None),
270    }
271}
272
273/// [`carry`] for ONE origin whose binding is not kept in this register: a
274/// handoff ledger, whose binding lies beside the ledger file. `origin` is
275/// that binding and `origin_text` the text it binds. The derived item — a
276/// finding or fact restored from the ledger — is bound to EVERY file the
277/// origin names, read again now; the three outcomes are those of [`carry`].
278///
279/// This over-approximates per item: the origin has no per-item spans, so an
280/// item is bound to all the origin's files, not only to those its own text
281/// came from. More sources must hold, never fewer.
282pub(crate) fn carry_from(
283    derived: &Item<'_>,
284    text: &str,
285    origin: &StoredBinding,
286    origin_text: &str,
287    reader_project: Option<&str>,
288) -> Result<Option<Carried>, Withheld> {
289    let enforced = stored::source_authority_required();
290    let held = match held_sources(origin, origin_text, reader_project) {
291        Ok(held) => held,
292        Err(withheld) if enforced => return Err(withheld),
293        Err(_) => None,
294    };
295    let Some((project, sources)) = held else {
296        return Ok(None);
297    };
298    carried(derived, text, &project, sources, enforced)
299}
300
301/// What a store that COPIES `text` of `item` into another stored unit (a
302/// handoff ledger) has to know about it, without delivering it:
303///
304/// - `Ok(Some((project, sources)))`: the item is bound and holds now — served
305///   to `reader_project`, every file re-read against the digest it was bound
306///   to. The copy inherits exactly these sources;
307/// - `Ok(None)`: no register entry for this text, or one that names no file.
308///   The copy is originless, as the item is;
309/// - `Err`: the item is bound and is not served now, or a source no longer
310///   delivers what it was bound to. The caller decides by the protection
311///   state whether the text may be copied at all.
312///
313/// Nothing is published into the call's capture ([`serve`] does that): the
314/// re-reads go through the admitted reader, which publishes every read, so
315/// they run outside the capture. A check that ends in a refusal — or an item
316/// its caller then does not copy — leaves no source behind.
317pub fn held(
318    item: &Item<'_>,
319    text: &str,
320    reader_project: Option<&str>,
321) -> Result<Option<(String, Vec<SourceRef>)>, Withheld> {
322    let Some(binding) = binding_of(item, text) else {
323        return Ok(None);
324    };
325    crate::core::archive::authority::without_capture(|| {
326        held_sources(&binding, text, reader_project)
327    })
328}
329
330/// Whether `item`, bound in ANOTHER checkout of the same project, holds in
331/// the reader's `checkout` (AP01 §4, `content` class): every file its
332/// binding names, at the same path relative to the checkout it was bound
333/// in, delivers in `checkout` exactly the bytes it was bound to — read now
334/// through the admitted reader for `checkout`, under its policy and role.
335/// Held, those files of `checkout` are published into the call's capture,
336/// so the reply carries the lineage of the reader's own files.
337///
338/// `false` — the item must not be served there — for an item without a
339/// binding of exactly `text`, a binding that names no file, a path that
340/// does not lie in the bound checkout, and any file that is missing,
341/// changed (another branch or revision) or no longer admitted. Refused
342/// re-reads leave nothing in the capture.
343pub fn holds_in_checkout(item: &Item<'_>, text: &str, checkout: &str) -> bool {
344    use std::path::{Component, Path, PathBuf};
345    let Some(binding) = binding_of(item, text) else {
346        return false;
347    };
348    let Some((bound_root, files)) = binding.file_sources() else {
349        return false;
350    };
351    let canonical = |path: &str| crate::core::pathutil::safe_canonicalize_or_self(Path::new(path));
352    let bound_roots = [PathBuf::from(bound_root), canonical(bound_root)];
353    let relative = |path: &str| -> Option<PathBuf> {
354        let candidates = [PathBuf::from(path), canonical(path)];
355        let relative = candidates.iter().find_map(|candidate| {
356            bound_roots
357                .iter()
358                .find_map(|root| candidate.strip_prefix(root).ok())
359        })?;
360        relative
361            .components()
362            .all(|part| matches!(part, Component::Normal(_)))
363            .then(|| relative.to_path_buf())
364    };
365    let checkout_root = canonical(checkout);
366    let Some(checkout_str) = checkout_root.to_str() else {
367        return false;
368    };
369    let held = crate::core::archive::authority::without_capture(|| {
370        files
371            .iter()
372            .map(|&(path, tool, digest)| {
373                let relative = relative(path)?;
374                let target = checkout_root.join(&relative);
375                SourceRef::read_as_admitted(target.to_str()?, checkout_str, tool, digest)?;
376                Some((relative, tool, digest))
377            })
378            .collect::<Option<Vec<_>>>()
379    });
380    let Some(held) = held else {
381        return false;
382    };
383    for (relative, tool, digest) in held {
384        if let Some(source) = ArchiveAuthority::admitted_source(
385            &checkout_root,
386            relative.to_str().unwrap_or_default(),
387            tool,
388            digest,
389        ) {
390            source.publish();
391        }
392    }
393    true
394}
395
396/// The binding of `item` if it is a binding of exactly `text`.
397fn binding_of(item: &Item<'_>, text: &str) -> Option<StoredBinding> {
398    REGISTER
399        .read::<StoredBinding>(&item.key(text), register::now())
400        .filter(|binding| binding.binds(text))
401}
402
403/// For the store that is about to deliver `text` of `item` to a reader in
404/// `reader_project`, while protection is active:
405///
406/// - a bound item is re-authorized (`stored::serve_stored`: project, every
407///   source re-read, classification, content rules). `Err`: the item must NOT
408///   be delivered — a bound item is as revocable as its sources. `Ok`: its
409///   files are published into the call's source capture;
410/// - an originless item marks the capture incomplete and returns `Ok`: whether
411///   it is delivered stays the decision of its store, as before.
412///
413/// Without protection nothing is checked or published.
414pub fn serve(item: &Item<'_>, text: &str, reader_project: Option<&str>) -> Result<(), Withheld> {
415    if !stored::source_authority_required() {
416        return Ok(());
417    }
418    let binding = binding_of(item, text);
419    if let Some(binding) = &binding {
420        stored::serve_stored(text, Some(binding), reader_project)?;
421    }
422    stored::publish_served(binding.as_ref());
423    Ok(())
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429    use crate::core::archive::delivered::LineageRefusal;
430    use crate::core::context_admission::stored::lineage_support::{
431        deliver, governed, project, reusable,
432    };
433    use crate::core::policy::runtime::TestPolicyOverride;
434
435    fn fact<'a>(project: &'a str, key: &'a str) -> Item<'a> {
436        Item::KnowledgeFact {
437            project,
438            category: "architecture",
439            key,
440        }
441    }
442
443    /// Deliver one fact the way a recall formats it.
444    fn recall(root: &str, item: &Item<'_>, value: &str) -> (String, usize) {
445        deliver(root, || match serve(item, value, Some(root)) {
446            Ok(()) => format!("[architecture] {value}"),
447            Err(withheld) => withheld.notice(),
448        })
449    }
450
451    /// A fact written with a source the admitted reader returned is bound,
452    /// its delivery is registered and fails with the source; the bound fact
453    /// itself is then withheld. A fact written without a source, and one
454    /// whose value was replaced after the binding, are originless.
455    #[test]
456    fn a_fact_is_bound_to_the_sources_named_at_its_write_only() {
457        let _data = governed();
458        let _community = TestPolicyOverride::set(None);
459        let (_directory, root) = project();
460        std::fs::write(format!("{root}/auth.rs"), "pub fn verify_rs256() {}\n").expect("source");
461        let value = "tokens are verified with RS256";
462        let bound_fact = fact(&root, "token-check");
463        let sources = sources_at(&root, &["auth.rs"], "ctx_knowledge").expect("readable source");
464        assert!(bind(&bound_fact, value, &root, sources));
465
466        let (reply, recorded) = recall(&root, &bound_fact, value);
467        assert!(reply.contains("RS256"), "{reply}");
468        assert_eq!(recorded, 1);
469        assert_eq!(reusable(&root, &reply), Ok(()));
470
471        // No source named: nothing is bound, the delivery is unknown.
472        let plain = fact(&root, "typed-note");
473        assert!(sources_at::<&str>(&root, &[], "ctx_knowledge").is_none());
474        assert!(!bind(&plain, "typed by the agent", &root, Vec::new()));
475        let (typed, recorded) = recall(&root, &plain, "typed by the agent");
476        assert!(typed.contains("typed by the agent"), "{typed}");
477        assert_eq!(recorded, 0);
478        assert_eq!(reusable(&root, &typed), Err(LineageRefusal::Unknown));
479
480        // The value is replaced without sources: the old binding is not a
481        // binding of the new text.
482        let (replaced, recorded) = recall(&root, &bound_fact, "tokens are opaque now");
483        assert!(replaced.contains("opaque"), "{replaced}");
484        assert_eq!(recorded, 0);
485
486        // A named source that cannot be bound binds nothing (E3, and never a
487        // partial lineage).
488        std::fs::write(format!("{root}/plan.md"), "*** TOP SECRET ***\nlaunch\n").expect("marked");
489        assert!(sources_at(&root, &["auth.rs", "plan.md"], "ctx_knowledge").is_none());
490        assert!(sources_at(&root, &["missing.rs"], "ctx_knowledge").is_none());
491        assert!(sources_at(&root, &["../outside.rs"], "ctx_knowledge").is_none());
492
493        // The source goes: the registered reply is refused, and the bound
494        // fact is no longer served.
495        std::fs::remove_file(format!("{root}/auth.rs")).expect("delete");
496        assert_eq!(
497            reusable(&root, &reply),
498            Err(LineageRefusal::SourceNoLongerAdmitted)
499        );
500        let (withheld, recorded) = recall(&root, &bound_fact, value);
501        assert!(!withheld.contains("RS256"), "{withheld}");
502        assert_eq!(recorded, 0);
503    }
504
505    /// `held` is a check, never a delivery. Its re-reads went through the
506    /// publishing reader inside the call's capture: an item that held left
507    /// its files there even when the next one was refused (or when its caller
508    /// did not copy it), so a refusal carried a file lineage.
509    #[test]
510    fn a_held_check_leaves_the_capture_untouched() {
511        use crate::core::archive::authority::capture_sync;
512        use crate::core::context_admission::stored::lineage_support::scoped;
513        let _data = governed();
514        let _community = TestPolicyOverride::set(None);
515        let (_directory, root) = project();
516        for name in ["auth.rs", "pool.rs"] {
517            std::fs::write(format!("{root}/{name}"), format!("pub fn {name}() {{}}\n"))
518                .expect("source");
519        }
520        let (holding, lapsed) = (fact(&root, "token-check"), fact(&root, "pool-size"));
521        for (item, value, file) in [
522            (&holding, "tokens are verified with RS256", "auth.rs"),
523            (&lapsed, "the pool holds eight leases", "pool.rs"),
524        ] {
525            let sources = sources_at(&root, &[file], "ctx_knowledge").expect("readable source");
526            assert!(bind(item, value, &root, sources));
527        }
528        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
529
530        let ((first, second), capture) = scoped(&root, || {
531            capture_sync(|| {
532                (
533                    held(&holding, "tokens are verified with RS256", Some(&root)),
534                    held(&lapsed, "the pool holds eight leases", Some(&root)),
535                )
536            })
537        });
538        let (project, sources) = first.expect("holds").expect("bound to a file");
539        assert_eq!(project, root);
540        assert_eq!(sources.len(), 1);
541        assert!(second.is_err(), "its source is gone");
542        assert!(
543            capture.is_none(),
544            "a check publishes nothing, held or refused"
545        );
546    }
547
548    /// A store written before bindings existed has no register entry: its
549    /// items are originless, and nothing is on disk for them.
550    #[test]
551    fn an_item_without_a_register_entry_is_originless() {
552        let data = governed();
553        let _community = TestPolicyOverride::set(None);
554        let (_directory, root) = project();
555        let finding = Item::SessionFinding {
556            session: "session-1",
557            file: Some("src/lib.rs"),
558        };
559        let (reply, recorded) = deliver(&root, || {
560            serve(&finding, "an old finding", Some(&root))
561                .expect("originless items are not refused");
562            "finding: an old finding".to_owned()
563        });
564        assert_eq!(recorded, 0);
565        assert_eq!(reusable(&root, &reply), Err(LineageRefusal::Unknown));
566        assert!(!data.path().join("archives").join("bindings").exists());
567    }
568
569    /// A finding derived from the output of a call is bound to that call's
570    /// complete source set.
571    #[test]
572    fn a_finding_is_bound_to_the_sources_of_the_call_that_produced_it() {
573        let _data = governed();
574        let _community = TestPolicyOverride::set(None);
575        let (_directory, root) = project();
576        let path = format!("{root}/build.rs");
577        std::fs::write(&path, "fn main() { panic!(\"linker\") }\n").expect("source");
578        let admitted =
579            crate::core::rooted_read::read_file_for_tool_rooted(&path, &root, "ctx_read")
580                .expect("admitted read");
581        // What the admitted reader publishes into the call's capture.
582        let capture =
583            ArchiveAuthority::file(std::path::Path::new(&root), &path, "ctx_read", &admitted)
584                .expect("protection is active: the read is bound");
585        let finding = Item::SessionFinding {
586            session: "session-1",
587            file: Some("build.rs"),
588        };
589        let summary = "build.rs panics in the linker step";
590        let sources = sources_of_call(&capture).expect("complete source set");
591        assert!(bind(&finding, summary, &root, sources));
592        let (reply, recorded) = deliver(&root, || {
593            serve(&finding, summary, Some(&root)).expect("bound and admitted");
594            format!("finding: {summary}")
595        });
596        assert_eq!(recorded, 1);
597        assert_eq!(reusable(&root, &reply), Ok(()));
598
599        std::fs::write(&path, "fn main() {}\n").expect("the source changes");
600        assert_eq!(
601            reusable(&root, &reply),
602            Err(LineageRefusal::SourceNoLongerAdmitted)
603        );
604    }
605}