1use 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#[derive(Debug, Clone, Copy)]
32pub enum Item<'a> {
33 KnowledgeFact {
35 project: &'a str,
36 category: &'a str,
37 key: &'a str,
38 },
39 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 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
79pub 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
99pub 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
111pub(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
126pub 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
135pub(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
156pub struct Carried(StoredBinding);
159
160impl Carried {
161 pub fn commit(self, item: &Item<'_>, text: &str) -> bool {
166 self.0.binds(text) && write(item, text, self.0)
167 }
168}
169
170fn 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
193pub(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
256fn 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
273pub(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
301pub 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
330pub 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
396fn 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
403pub 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 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 #[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 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 let (replaced, recorded) = recall(&root, &bound_fact, "tokens are opaque now");
483 assert!(replaced.contains("opaque"), "{replaced}");
484 assert_eq!(recorded, 0);
485
486 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 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 #[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 #[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 #[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 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}