1mod bounded;
6pub mod claude_code;
7pub mod codex;
8pub mod cursor;
9pub(crate) mod database;
10pub mod git_history;
11pub mod markdown;
12pub mod opencode;
13mod staging;
14
15use std::collections::HashSet;
16use std::path::{Path, PathBuf};
17
18use lean_ctx_time::UtcDateTime;
19use serde_json::Value;
20
21use crate::core::knowledge::KnowledgeFact;
22use staging::{Gateway, Origin, Rules, joined_leaves, mask_strings};
23
24const MAX_FACT_VALUE_CHARS: usize = 500;
25const MAX_ERRORS: usize = 100;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ImportSource {
29 ClaudeCode,
30 Codex,
31 Cursor,
32 OpenCode,
33 Docs,
35 Git,
37}
38
39impl ImportSource {
40 #[must_use]
41 pub const fn as_str(self) -> &'static str {
42 match self {
43 Self::ClaudeCode => "claude-code",
44 Self::Codex => "codex",
45 Self::Cursor => "cursor",
46 Self::OpenCode => "opencode",
47 Self::Docs => "docs",
48 Self::Git => "git",
49 }
50 }
51}
52
53#[derive(Debug, Clone, Default)]
54pub struct ImportResult {
55 pub sessions_found: usize,
56 pub facts_extracted: usize,
57 pub files_touched: usize,
58 pub errors: Vec<String>,
59 pub facts: Vec<KnowledgeFact>,
61 pub facts_skipped: usize,
64 pub sources_skipped: usize,
68 pub sources_refused: usize,
72 pub repo_scope: Option<RepoScope>,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct RepoScope {
82 pub files: Vec<String>,
83 pub whole: bool,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum SourceRefusal {
90 OutsideRoot,
92 Withheld,
95 TooLarge,
100 RecordTooLarge,
104 UnitAdmissionUnsupported,
111 TooManyFacts,
115 Changed,
118 Unreadable,
120 DatabaseUnreadable,
123 UnsupportedSchema,
125}
126#[derive(Debug, Clone, PartialEq, Eq)]
130pub(crate) struct HistorySource {
131 pub root: PathBuf,
132 pub path: PathBuf,
133}
134
135pub(crate) fn resolve_history_source(
155 history_root: &Path,
156 path: &Path,
157) -> Result<HistorySource, SourceRefusal> {
158 let request = crate::core::admitted_sources::request_root();
159 let named = [PathBuf::from(request), history_root.to_path_buf()];
160 let path = path.canonicalize().map_err(|_| SourceRefusal::Unreadable)?;
161 named
162 .iter()
163 .filter(|root| !root.as_os_str().is_empty())
164 .filter_map(|root| root.canonicalize().ok())
165 .find(|root| path.starts_with(root))
166 .map(|root| HistorySource { root, path })
167 .ok_or(SourceRefusal::OutsideRoot)
168}
169
170pub(crate) fn admit_history_database(
187 history_root: &Path,
188 path: &Path,
189) -> Result<HistorySource, SourceRefusal> {
190 let source = resolve_history_source(history_root, path)?;
191 crate::core::io_boundary::jail_and_check_path("ctx_knowledge", &source.path, &source.root)
192 .map_err(|_| SourceRefusal::Withheld)?;
193 Ok(source)
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub(crate) enum ValueRefusal {
199 Withheld,
201 NotStorable,
204}
205
206#[derive(Debug, Clone)]
225pub(crate) struct AdmittedValue(Value);
226
227impl AdmittedValue {
228 pub(crate) fn admit(original: Value, rules: Rules<'_>) -> Result<Self, ValueRefusal> {
244 let joined = joined_leaves(&original);
245 if joined.is_empty() {
246 return Ok(Self(original));
247 }
248 if admitted_text(&joined, rules)? == joined {
249 return Ok(Self(original));
250 }
251 let mut masked = original;
252 mask_strings(&mut masked, rules)?;
253 let rejoined = joined_leaves(&masked);
254 if admitted_text(&rejoined, rules)? != rejoined {
255 return Err(ValueRefusal::Withheld);
256 }
257 Ok(Self(masked))
258 }
259
260 fn of_admitted_source(value: Value) -> Self {
264 Self(value)
265 }
266
267 #[allow(clippy::unused_self)]
270 pub(crate) fn derive(&self, value: Value) -> Self {
271 Self(value)
272 }
273
274 pub(crate) fn value(&self) -> &Value {
275 &self.0
276 }
277}
278
279fn admitted_text(text: &str, rules: Rules<'_>) -> Result<String, ValueRefusal> {
281 let admission = crate::core::context_admission::carrier::admit_carrier_text_under(
282 text,
283 rules,
284 &crate::core::context_admission::carrier::STORED,
285 )
286 .map_err(|_| ValueRefusal::Withheld)?;
287 if admission.storable {
288 Ok(admission.text)
289 } else {
290 Err(ValueRefusal::NotStorable)
291 }
292}
293
294#[cfg(test)]
297pub(crate) fn admit_column(result: &mut ImportResult, original: Value) -> Option<AdmittedValue> {
298 match AdmittedValue::admit(original, None) {
299 Ok(value) => Some(value),
300 Err(ValueRefusal::Withheld | ValueRefusal::NotStorable) => {
301 result.facts_skipped += 1;
302 None
303 }
304 }
305}
306
307impl ImportResult {
308 pub fn merge(&mut self, mut other: Self) {
309 self.sessions_found += other.sessions_found;
310 self.facts_extracted += other.facts_extracted;
311 self.files_touched += other.files_touched;
312 self.facts_skipped += other.facts_skipped;
313 self.sources_skipped += other.sources_skipped;
314 self.sources_refused += other.sources_refused;
315 self.errors.append(&mut other.errors);
316 self.facts.append(&mut other.facts);
317 }
318
319 pub(crate) fn refuse(&mut self, refusal: SourceRefusal) {
322 match refusal {
323 SourceRefusal::OutsideRoot | SourceRefusal::Withheld | SourceRefusal::Changed => {
324 self.sources_refused += 1;
325 }
326 SourceRefusal::TooLarge
327 | SourceRefusal::RecordTooLarge
328 | SourceRefusal::UnitAdmissionUnsupported
329 | SourceRefusal::TooManyFacts
330 | SourceRefusal::DatabaseUnreadable
331 | SourceRefusal::UnsupportedSchema
332 | SourceRefusal::Unreadable => self.sources_skipped += 1,
333 }
334 }
335}
336
337pub(crate) fn home_dir() -> Option<PathBuf> {
338 std::env::var_os("HOME").map(PathBuf::from)
339}
340
341fn scratch_parent() -> std::io::Result<PathBuf> {
345 let directory = crate::core::data_dir::lean_ctx_data_dir().map_err(std::io::Error::other)?;
346 std::fs::create_dir_all(&directory)?;
347 Ok(directory)
348}
349
350fn read_transcript(root: &Path, path: &Path, gateway: &Gateway) -> Result<String, SourceRefusal> {
362 use crate::core::admitted_sources::{self, SourceRead};
363 let source = resolve_history_source(root, path)?;
364 let size = std::fs::metadata(&source.path)
365 .map_err(|_| SourceRefusal::Unreadable)?
366 .len();
367 if size > crate::core::limits::max_read_bytes() as u64 {
368 return Err(SourceRefusal::TooLarge);
369 }
370 match admitted_sources::read_with_admission(
371 &source.root.to_string_lossy(),
372 &source.path.to_string_lossy(),
373 "ctx_knowledge",
374 gateway,
375 ) {
376 read @ SourceRead::Admitted(_) => read
377 .storable()
378 .map(str::to_owned)
379 .ok_or(SourceRefusal::Withheld),
380 SourceRead::Withheld(_) => Err(SourceRefusal::Withheld),
381 SourceRead::Unavailable(_) => Err(SourceRefusal::Unreadable),
382 }
383}
384
385fn for_each_transcript_line(
397 root: &Path,
398 path: &Path,
399 gateway: &Gateway,
400 mut each: impl FnMut(usize, &str),
401) -> Result<(), SourceRefusal> {
402 match read_transcript(root, path, gateway) {
403 Ok(content) => {
404 for (index, line) in content.lines().enumerate() {
405 each(index + 1, line);
406 }
407 Ok(())
408 }
409 Err(SourceRefusal::TooLarge) => {
410 let source = resolve_history_source(root, path)?;
411 let mut line_number = 0;
412 pinned(&source, || {
413 bounded::admit(&source, gateway)?.for_each_unit(|unit| {
414 for line in unit.lines() {
415 line_number += 1;
416 each(line_number, line);
417 }
418 })
419 })
420 }
421 Err(refusal) => Err(refusal),
422 }
423}
424
425fn pinned<T>(
436 source: &HistorySource,
437 read: impl FnOnce() -> Result<T, SourceRefusal>,
438) -> Result<T, SourceRefusal> {
439 crate::core::policy::runtime::with_project_source_view(&source.root.to_string_lossy(), read)
440 .unwrap_or(Err(SourceRefusal::Withheld))
441}
442
443pub(crate) fn read_jsonl_files(
444 source: ImportSource,
445 root: &Path,
446 files: Vec<PathBuf>,
447) -> ImportResult {
448 let mut result = ImportResult {
449 sessions_found: files.len(),
450 ..ImportResult::default()
451 };
452 let mut touched = HashSet::new();
453 let mut seen = HashSet::new();
454
455 for path in files {
456 let gateway = crate::core::context_admission::carrier::gateway_snapshot();
460 let mut pending = staging::Pending::under(gateway.clone());
461 let session = session_id(source, &path, pending.rules());
462 let read = for_each_transcript_line(root, &path, &gateway, |line_number, line| {
463 if line.trim().is_empty() {
464 return;
465 }
466 match serde_json::from_str::<Value>(line) {
467 Ok(value) => staging::select(&AdmittedValue::of_admitted_source(value), |found| {
468 pending.stage(found);
469 }),
470 Err(error) => pending.error(format!(
471 "{}:{line_number}: invalid JSONL: {error}",
472 path.display()
473 )),
474 }
475 });
476 let _ = pending.settle(read, source, &session, &mut result, &mut touched, &mut seen);
477 }
478
479 result.files_touched = touched.len();
480 result.facts_extracted = result.facts.len();
481 result
482}
483
484pub(crate) fn read_json_file(source: ImportSource, root: &Path, path: &Path) -> ImportResult {
485 let mut result = ImportResult {
486 sessions_found: 1,
487 ..ImportResult::default()
488 };
489 let mut touched = HashSet::new();
490 let mut seen = HashSet::new();
491 let gateway = crate::core::context_admission::carrier::gateway_snapshot();
492 let rules = Some(gateway.admission_policy());
493 let session = session_id(source, path, rules);
494 match read_transcript(root, path, &gateway) {
495 Err(refusal) => result.refuse(refusal),
496 Ok(content) => match serde_json::from_str::<Value>(&content) {
497 Ok(value) => process_admitted(
498 Origin::new(source, &session, rules),
499 &AdmittedValue::of_admitted_source(value),
500 &mut result,
501 &mut touched,
502 &mut seen,
503 ),
504 Err(error) => push_error(
505 &mut result,
506 format!("{}: invalid JSON: {error}", path.display()),
507 ),
508 },
509 }
510
511 result.files_touched = touched.len();
512 result.facts_extracted = result.facts.len();
513 result
514}
515
516#[cfg(test)]
520pub(crate) fn process_value(
521 source: ImportSource,
522 session: &str,
523 value: &Value,
524 result: &mut ImportResult,
525 touched: &mut HashSet<String>,
526 seen: &mut HashSet<(String, String)>,
527) {
528 if let Some(admitted) = admit_column(result, value.clone()) {
529 let origin = Origin::new(source, session, None);
530 process_admitted(origin, &admitted, result, touched, seen);
531 }
532}
533
534fn process_admitted(
538 origin: Origin<'_>,
539 value: &AdmittedValue,
540 result: &mut ImportResult,
541 touched: &mut HashSet<String>,
542 seen: &mut HashSet<(String, String)>,
543) {
544 staging::select(value, |found| {
547 staging::take_over(found, origin, result, touched, seen);
548 });
549}
550
551pub(crate) fn finish_result(result: &mut ImportResult, touched: &HashSet<String>) {
552 result.files_touched = touched.len();
553 result.facts_extracted = result.facts.len();
554}
555
556pub(crate) fn push_error(result: &mut ImportResult, error: String) {
557 if result.errors.len() < MAX_ERRORS {
558 result.errors.push(error);
559 }
560}
561
562pub(crate) fn session_id(source: ImportSource, path: &Path, rules: Rules<'_>) -> String {
563 let name = path
564 .file_name()
565 .and_then(|name| name.to_str())
566 .unwrap_or("unknown-session");
567 session_label(source, name, rules)
568}
569
570pub(crate) fn session_label(source: ImportSource, name: &str, rules: Rules<'_>) -> String {
576 let kept = crate::core::context_admission::carrier::admit_for_store_under(name, rules)
577 .is_ok_and(|admitted| admitted == name);
578 let name = if kept { name } else { "unnamed-session" };
579 format!("{}:{name}", source.as_str())
580}
581
582fn push_fact(
583 result: &mut ImportResult,
584 seen: &mut HashSet<(String, String)>,
585 Origin {
586 source,
587 session,
588 rules,
589 }: Origin<'_>,
590 category: &str,
591 value: &str,
592 confidence: f32,
593) {
594 let value = truncate(value);
595 if value.is_empty() || !seen.insert((category.to_owned(), value.clone())) {
596 return;
597 }
598 let admitted = crate::core::context_admission::carrier::admit_for_store_under(&value, rules);
605 let Ok(value) = admitted else {
606 result.facts_skipped += 1;
607 return;
608 };
609 if value.is_empty() {
610 return;
611 }
612
613 let now = UtcDateTime::now();
614 result.facts.push(KnowledgeFact {
615 anchors: Vec::new(),
616 review: None,
617 capture: Default::default(),
618 origin: crate::core::knowledge::FactOrigin::Unverified,
619 category: category.to_owned(),
620 key: String::new(),
621 value,
622 source_session: session.to_owned(),
623 confidence,
624 created_at: now,
625 last_confirmed: now,
626 retrieval_count: 0,
627 last_retrieved: None,
628 valid_from: None,
629 valid_until: None,
630 supersedes: None,
631 confirmation_count: 0,
632 feedback_up: 0,
633 feedback_down: 0,
634 last_feedback: None,
635 privacy: Default::default(),
636 sensitivity: Default::default(),
637 imported_from: Some(source.as_str().to_owned()),
638 archetype: Default::default(),
639 fidelity: None,
640 revision_count: 0,
641 status: None,
642 validity: None,
643 });
644}
645
646pub(crate) struct RepoFact {
649 pub category: &'static str,
650 pub key: String,
653 pub value: String,
654 pub confidence: f32,
655 pub validity: Option<crate::core::knowledge::FactValidity>,
656 pub valid_from: Option<lean_ctx_time::UtcDateTime>,
657 pub anchors: Vec<crate::core::knowledge::anchors::CodeAnchor>,
659}
660
661pub(crate) fn push_repo_fact(
666 result: &mut ImportResult,
667 seen: &mut HashSet<(String, String)>,
668 source: ImportSource,
669 session: &str,
670 rules: Rules<'_>,
671 fact: RepoFact,
672) {
673 let value = truncate(&fact.value);
674 if value.is_empty() || !seen.insert((fact.category.to_owned(), value.clone())) {
675 return;
676 }
677 let Ok(value) = crate::core::context_admission::carrier::admit_for_store_under(&value, rules)
678 else {
679 result.facts_skipped += 1;
680 return;
681 };
682 if value.is_empty() {
683 return;
684 }
685 let now = UtcDateTime::now();
686 result.facts.push(KnowledgeFact {
687 origin: crate::core::knowledge::FactOrigin::Unverified,
688 category: fact.category.to_owned(),
689 key: fact.key,
690 value,
691 source_session: session.to_owned(),
692 confidence: fact.confidence,
693 created_at: now,
694 last_confirmed: now,
695 retrieval_count: 0,
696 last_retrieved: None,
697 valid_from: fact.valid_from,
698 valid_until: None,
699 supersedes: None,
700 confirmation_count: 0,
701 feedback_up: 0,
702 feedback_down: 0,
703 last_feedback: None,
704 privacy: Default::default(),
705 sensitivity: Default::default(),
706 imported_from: Some(source.as_str().to_owned()),
707 archetype: crate::core::knowledge::KnowledgeArchetype::infer_from_category(fact.category),
708 fidelity: None,
709 revision_count: 0,
710 status: None,
711 validity: fact.validity,
712 anchors: fact.anchors,
713 review: None,
714 capture: Default::default(),
715 });
716}
717
718fn collect_file_paths(value: &Value, out: &mut Vec<String>) {
719 match value {
720 Value::Array(values) => {
721 for value in values {
722 collect_file_paths(value, out);
723 }
724 }
725 Value::Object(map) => {
726 for (key, value) in map {
727 if matches!(
728 key.as_str(),
729 "file_path" | "filePath" | "path" | "filename" | "file_name"
730 ) {
731 if let Some(path) = value
732 .as_str()
733 .map(str::trim)
734 .filter(|path| !path.is_empty())
735 {
736 out.push(path.to_owned());
737 }
738 }
739 collect_file_paths(value, out);
740 }
741 }
742 _ => {}
743 }
744}
745
746fn collect_strings(value: &Value, out: &mut Vec<String>) {
747 match value {
748 Value::String(text) => out.push(text.to_owned()),
749 Value::Array(values) => {
750 for value in values {
751 collect_strings(value, out);
752 }
753 }
754 Value::Object(map) => {
755 for value in map.values() {
756 collect_strings(value, out);
757 }
758 }
759 _ => {}
760 }
761}
762
763fn contains_assistant_message(value: &Value) -> bool {
764 match value {
765 Value::Array(values) => values.iter().any(contains_assistant_message),
766 Value::Object(map) => {
767 map.get("role").and_then(Value::as_str) == Some("assistant")
768 || matches!(
769 map.get("type").and_then(Value::as_str),
770 Some("assistant" | "assistant_message")
771 )
772 || map.values().any(contains_assistant_message)
773 }
774 _ => false,
775 }
776}
777
778fn matching_snippets(text: &str, predicate: fn(&str) -> bool) -> Vec<String> {
779 text.split(['\n', '.', '!', '?'])
780 .map(str::trim)
781 .filter(|snippet| snippet.len() >= 4 && predicate(snippet))
782 .map(str::to_owned)
783 .collect()
784}
785
786fn is_decision(text: &str) -> bool {
787 let text = text.to_ascii_lowercase();
788 [
789 "decision",
790 "decided",
791 "we chose",
792 "i chose",
793 "chosen",
794 "will use",
795 "we'll use",
796 "we will use",
797 "going with",
798 "approach is",
799 ]
800 .iter()
801 .any(|marker| text.contains(marker))
802}
803
804fn is_error(text: &str) -> bool {
805 let text = text.to_ascii_lowercase();
806 [
807 "error",
808 "failed",
809 "failure",
810 "panic",
811 "unable to",
812 "cannot ",
813 "can't ",
814 ]
815 .iter()
816 .any(|marker| text.contains(marker))
817}
818
819fn truncate(value: &str) -> String {
820 value[..value.floor_char_boundary(MAX_FACT_VALUE_CHARS)]
826 .trim()
827 .to_owned()
828}
829
830#[cfg(test)]
831mod tests {
832 use super::*;
833
834 #[test]
835 fn truncates_multibyte_facts_without_panicking() {
836 let value = format!("We decided {}", "é".repeat(300));
837 let truncated = truncate(&value);
838 assert!(truncated.len() <= MAX_FACT_VALUE_CHARS);
839 assert!(truncated.is_char_boundary(truncated.len()));
840 }
841
842 #[test]
843 fn extracts_touches_decisions_and_errors() {
844 let value: Value = serde_json::json!({
845 "role": "assistant",
846 "content": "We decided to use a cache. Build failed because input is invalid.",
847 "tool_input": { "file_path": "rust/src/lib.rs" }
848 });
849 let mut result = ImportResult::default();
850 let mut touched = HashSet::new();
851 let mut seen = HashSet::new();
852
853 process_value(
854 ImportSource::Codex,
855 "codex:test",
856 &value,
857 &mut result,
858 &mut touched,
859 &mut seen,
860 );
861 finish_result(&mut result, &touched);
862
863 assert_eq!(result.files_touched, 1);
864 assert!(
865 result
866 .facts
867 .iter()
868 .any(|fact| fact.category == "imported-decision")
869 );
870 assert!(
871 result
872 .facts
873 .iter()
874 .any(|fact| fact.value.starts_with("Observed error:"))
875 );
876 }
877
878 const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
879
880 fn history() -> (tempfile::TempDir, PathBuf, PathBuf) {
883 let dir = tempfile::tempdir().expect("history dir");
884 let root = dir.path().canonicalize().expect("history root");
885 let sessions = root.join("project-a");
886 std::fs::create_dir_all(&sessions).expect("session dir");
887 (dir, root, sessions)
888 }
889
890 fn assistant_line(text: &str) -> String {
891 serde_json::json!({ "message": { "role": "assistant", "content": text } }).to_string()
892 }
893
894 fn decisions(result: &ImportResult) -> Vec<&str> {
895 result
896 .facts
897 .iter()
898 .filter(|fact| fact.category == "imported-decision")
899 .map(|fact| fact.value.as_str())
900 .collect()
901 }
902
903 #[test]
908 fn a_transcript_is_read_admitted_and_its_facts_are_admitted_where_they_are_built() {
909 let _data = crate::core::data_dir::isolated_data_dir();
910 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
911 let (_dir, root, sessions) = history();
912 std::fs::write(
913 sessions.join("session.jsonl"),
914 format!(
915 "{}\n{}\n",
916 assistant_line("We decided to use JWT RS256 for the session tokens"),
917 assistant_line(&format!(
918 "We decided to deploy with the key {AWS_KEY} today"
919 )),
920 ),
921 )
922 .expect("transcript");
923
924 let result = claude_code::import_from_root(&root);
925 assert!(result.errors.is_empty(), "{:?}", result.errors);
926 assert_eq!(result.sessions_found, 1);
927 let decisions = decisions(&result);
928 assert!(
929 decisions.contains(&"We decided to use JWT RS256 for the session tokens"),
930 "a clean fact keeps its bytes: {decisions:?}"
931 );
932 assert!(
933 result
934 .facts
935 .iter()
936 .all(|fact| !fact.value.contains(AWS_KEY)),
937 "stored masked, or skipped — never raw"
938 );
939 assert_eq!(decisions.len() + result.facts_skipped, 2);
941 assert_eq!(result.facts_extracted, result.facts.len());
942 }
943
944 #[test]
947 fn a_restricted_value_is_skipped_and_counted() {
948 let _data = crate::core::data_dir::isolated_data_dir();
949 let policy = crate::core::policy::load(
950 "name = \"import-admission-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
951 [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
952 )
953 .expect("policy");
954 let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(policy));
955 let mut result = ImportResult::default();
956 let mut seen = HashSet::new();
957
958 for value in [
959 "We decided to use a cache",
960 "CONFIDENTIAL\nWe decided to ship roadmap-marker in May",
961 "CONFIDENTIAL\nWe decided to ship roadmap-marker in May",
963 ] {
964 push_fact(
965 &mut result,
966 &mut seen,
967 Origin::new(ImportSource::Codex, "codex:test", None),
968 "imported-decision",
969 value,
970 0.65,
971 );
972 }
973
974 assert_eq!(decisions(&result), vec!["We decided to use a cache"]);
975 assert_eq!(result.facts_skipped, 1);
976 assert!(result.errors.is_empty(), "nothing is reported about it");
977
978 let mut merged = ImportResult::default();
979 merged.merge(result);
980 assert_eq!(merged.facts_skipped, 1, "the count survives a merge");
981 }
982
983 #[cfg(unix)]
986 #[test]
987 fn a_transcript_outside_every_root_is_not_read() {
988 let _data = crate::core::data_dir::isolated_data_dir();
989 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
990 let (_dir, root, sessions) = history();
991 let elsewhere = tempfile::tempdir().expect("outside dir");
992 let outside = elsewhere
993 .path()
994 .canonicalize()
995 .expect("outside root")
996 .join("outside.jsonl");
997 std::fs::write(
998 &outside,
999 format!(
1000 "{}\n",
1001 assistant_line("We decided to keep outside-marker secret")
1002 ),
1003 )
1004 .expect("outside transcript");
1005 std::os::unix::fs::symlink(&outside, sessions.join("linked.jsonl")).expect("symlink");
1006
1007 let result = claude_code::import_from_root(&root);
1008 assert!(result.facts.is_empty(), "{:?}", decisions(&result));
1009 assert_eq!(result.facts_skipped, 0, "not read, so nothing was judged");
1010 assert_eq!(result.sources_refused, 1, "counted as refused");
1011 assert!(
1012 result.errors.is_empty(),
1013 "no path, no text: {:?}",
1014 result.errors
1015 );
1016
1017 let inside = sessions.join("inside.jsonl");
1020 std::fs::write(&inside, "{}\n").expect("inside transcript");
1021 assert_eq!(
1022 resolve_history_source(&root, &inside),
1023 Ok(HistorySource {
1024 root: root.clone(),
1025 path: inside,
1026 })
1027 );
1028 assert_eq!(
1029 resolve_history_source(&root, &outside),
1030 Err(SourceRefusal::OutsideRoot)
1031 );
1032 assert_eq!(
1033 resolve_history_source(&root, &sessions.join("linked.jsonl")),
1034 Err(SourceRefusal::OutsideRoot),
1035 "a link inside the root that points outside"
1036 );
1037 assert_eq!(
1038 resolve_history_source(&root, &root.join("missing.db")),
1039 Err(SourceRefusal::Unreadable)
1040 );
1041 assert!(
1042 !SourceRefusal::OutsideRoot
1043 .to_string()
1044 .contains("outside.jsonl")
1045 );
1046 }
1047
1048 #[test]
1053 fn history_files_inside_their_named_roots_are_read() {
1054 let _data = crate::core::data_dir::isolated_data_dir();
1055 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1056 let home = tempfile::tempdir().expect("home");
1057 let home = home.path().canonicalize().expect("home root");
1058
1059 let claude_root = home.join(".claude").join("projects");
1060 let claude_sessions = claude_root.join("-Users-dev-project");
1061 std::fs::create_dir_all(&claude_sessions).expect("claude dir");
1062 std::fs::write(
1063 claude_sessions.join("0b1c.jsonl"),
1064 format!(
1065 "{}\n",
1066 assistant_line("We decided to keep the claude marker")
1067 ),
1068 )
1069 .expect("claude transcript");
1070 let claude = claude_code::import_from_root(&claude_root);
1071 assert_eq!((claude.sources_refused, claude.sources_skipped), (0, 0));
1072 assert!(claude.errors.is_empty(), "{:?}", claude.errors);
1073 assert_eq!(
1074 decisions(&claude),
1075 vec!["We decided to keep the claude marker"]
1076 );
1077
1078 let codex_root = home.join(".codex");
1079 let codex_sessions = codex_root.join("sessions").join("2026");
1080 std::fs::create_dir_all(&codex_sessions).expect("codex dir");
1081 std::fs::write(
1082 codex_sessions.join("rollout-1.jsonl"),
1083 format!(
1084 "{}\n",
1085 assistant_line("We decided to keep the codex marker")
1086 ),
1087 )
1088 .expect("codex transcript");
1089 let codex = codex::import_from_root(&codex_root);
1090 assert_eq!((codex.sources_refused, codex.sources_skipped), (0, 0));
1091 assert!(codex.errors.is_empty(), "{:?}", codex.errors);
1092 assert_eq!(
1093 decisions(&codex),
1094 vec!["We decided to keep the codex marker"]
1095 );
1096 }
1097
1098 #[test]
1103 fn a_transcript_above_the_read_cap_is_skipped_and_counted() {
1104 let _data = crate::core::data_dir::isolated_data_dir();
1105 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1106 let (_dir, root, sessions) = history();
1107 let first = assistant_line("We decided to keep the early marker");
1108 let filler = assistant_line(&"x".repeat(4096));
1109 std::fs::write(sessions.join("large.jsonl"), format!("{first}\n{filler}\n"))
1110 .expect("large transcript");
1111
1112 crate::test_env::set_var("LCTX_MAX_READ_BYTES", "1024");
1113 let result = claude_code::import_from_root(&root);
1114 let rules = crate::core::context_admission::carrier::gateway_snapshot();
1115 let reason = resolve_history_source(&root, &sessions.join("large.jsonl"))
1116 .and_then(|source| pinned(&source, || bounded::admit(&source, &rules).map(|_| ())));
1117 crate::test_env::remove_var("LCTX_MAX_READ_BYTES");
1118
1119 assert_eq!(reason, Err(SourceRefusal::RecordTooLarge));
1120 assert_eq!(result.sources_skipped, 1);
1121 assert_eq!(result.sources_refused, 0);
1122 assert!(result.facts.is_empty(), "not even the part below the cap");
1123 assert!(result.errors.is_empty(), "{:?}", result.errors);
1124 }
1125
1126 #[test]
1129 fn a_session_label_is_kept_only_if_it_is_admitted_unchanged() {
1130 let _data = crate::core::data_dir::isolated_data_dir();
1131 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1132 assert_eq!(
1133 session_label(ImportSource::OpenCode, "ses_01HZX", None),
1134 "opencode:ses_01HZX"
1135 );
1136 let label = session_label(
1137 ImportSource::Codex,
1138 &format!("rollout {AWS_KEY}.jsonl"),
1139 None,
1140 );
1141 assert_eq!(label, "codex:unnamed-session");
1142 }
1143
1144 const BLOCK_CONFIDENTIAL: &str = "name = \"import-original-test\"\nversion = \"1.0.0\"\n\
1145 description = \"test\"\n[filters]\nclassification = \"block\"\n\
1146 blocked_labels = [\"CONFIDENTIAL\"]\n";
1147
1148 fn block_confidential() -> crate::core::policy::runtime::TestPolicyOverride {
1149 let policy = crate::core::policy::load(BLOCK_CONFIDENTIAL).expect("policy");
1150 crate::core::policy::runtime::TestPolicyOverride::set(Some(policy))
1151 }
1152
1153 fn codex_database(path: &Path, rows: &[&str]) {
1155 let db = rusqlite::Connection::open(path).expect("database");
1156 db.execute_batch("CREATE TABLE history (id INTEGER PRIMARY KEY, body TEXT NOT NULL);")
1157 .expect("schema");
1158 for row in rows {
1159 db.execute("INSERT INTO history (body) VALUES (?1)", [row])
1160 .expect("row");
1161 }
1162 }
1163
1164 #[test]
1168 fn a_marker_anywhere_in_an_original_value_refuses_the_whole_value() {
1169 let _data = crate::core::data_dir::isolated_data_dir();
1170 let _policy = block_confidential();
1171 let marked = serde_json::json!({
1172 "role": "assistant",
1173 "content": "We decided to keep the marked sentence",
1174 "banner": "CONFIDENTIAL",
1175 });
1176 assert!(AdmittedValue::admit(marked.clone(), None).is_err());
1177
1178 let mut result = ImportResult::default();
1179 assert!(admit_column(&mut result, marked).is_none());
1180 assert_eq!(result.facts_skipped, 1, "counted once per original value");
1181
1182 let clean = serde_json::json!({
1183 "role": "assistant",
1184 "content": "We decided to use a bounded cache",
1185 });
1186 let admitted = AdmittedValue::admit(clean.clone(), None).expect("a clean value");
1187 assert_eq!(admitted.value(), &clean, "a clean value keeps its bytes");
1188 let derived = admitted.derive(serde_json::json!({ "role": "assistant" }));
1189 assert_eq!(derived.value()["role"], "assistant");
1190 }
1191
1192 #[test]
1194 fn a_masked_original_is_only_ever_seen_masked() {
1195 let _data = crate::core::data_dir::isolated_data_dir();
1196 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1197 let keyed = serde_json::json!({
1198 "role": "assistant",
1199 "content": format!("We decided to deploy today. The key is {AWS_KEY}"),
1200 });
1201 match AdmittedValue::admit(keyed, None) {
1202 Ok(admitted) => {
1203 let text = admitted.value().to_string();
1204 assert!(!text.contains(AWS_KEY), "{text}");
1205 assert!(text.contains("We decided to deploy today"), "{text}");
1206 }
1207 Err(refusal) => assert!(
1209 matches!(refusal, ValueRefusal::NotStorable | ValueRefusal::Withheld),
1210 "{refusal:?}"
1211 ),
1212 }
1213 }
1214
1215 #[test]
1218 fn a_marked_codex_column_value_yields_no_fact() {
1219 let _data = crate::core::data_dir::isolated_data_dir();
1220 let (_dir, root, _sessions) = history();
1221 codex_database(
1222 &root.join("history.sqlite"),
1223 &[
1224 r#"{"role":"assistant","content":"We decided to keep the marked sentence","banner":"CONFIDENTIAL"}"#,
1225 r#"{"role":"assistant","content":"We decided to use a bounded cache"}"#,
1226 ],
1227 );
1228
1229 let _policy = block_confidential();
1230 let result = codex::import_from_root(&root);
1231 assert_eq!(
1232 decisions(&result),
1233 vec!["We decided to use a bounded cache"]
1234 );
1235 assert_eq!(result.facts_skipped, 1);
1236 assert_eq!((result.sources_refused, result.sources_skipped), (0, 0));
1237 assert!(
1238 result
1239 .facts
1240 .iter()
1241 .all(|fact| !fact.value.contains("marked sentence"))
1242 );
1243
1244 let broken = rusqlite::Connection::open(root.join("broken.sqlite")).expect("database");
1249 broken
1250 .execute_batch(
1251 "CREATE TABLE history (id INTEGER PRIMARY KEY, body TEXT NOT NULL); \
1252 INSERT INTO history (body) VALUES \
1253 ('{\"role\":\"assistant\",\"content\":\"We decided to keep the early row\"}'), \
1254 ('not json'); \
1255 ALTER TABLE history ADD COLUMN kind TEXT \
1256 GENERATED ALWAYS AS (json_extract(body, '$.role')) VIRTUAL;",
1257 )
1258 .expect("fixture");
1259 drop(broken);
1260 let again = codex::import_from_root(&root);
1261 assert_eq!(decisions(&again), decisions(&result));
1262 assert_eq!((again.sources_skipped, again.sources_refused), (1, 0));
1263 assert_eq!(
1264 (again.sessions_found, again.facts_skipped),
1265 (result.sessions_found, 1)
1266 );
1267 assert_eq!(again.errors.len(), 1, "{:?}", again.errors);
1268 assert!(again.errors[0].ends_with(": history database could not be read; skipped"));
1269 }
1270
1271 #[test]
1274 fn a_keyed_codex_column_value_never_yields_the_key() {
1275 let _data = crate::core::data_dir::isolated_data_dir();
1276 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1277 let (_dir, root, _sessions) = history();
1278 let row = serde_json::json!({
1279 "role": "assistant",
1280 "content": format!("We decided to deploy today. The key is {AWS_KEY}"),
1281 })
1282 .to_string();
1283 codex_database(&root.join("history.sqlite"), &[&row]);
1284
1285 let result = codex::import_from_root(&root);
1286 assert_eq!(result.sources_refused, 0);
1287 assert!(
1288 result
1289 .facts
1290 .iter()
1291 .all(|fact| !fact.value.contains(AWS_KEY))
1292 );
1293 if result.facts_skipped == 0 {
1294 assert!(
1295 decisions(&result).contains(&"We decided to deploy today"),
1296 "the clean sentence of the masked value is imported: {:?}",
1297 decisions(&result)
1298 );
1299 }
1300 }
1301
1302 #[test]
1306 fn a_marked_transcript_yields_no_fact() {
1307 let _data = crate::core::data_dir::isolated_data_dir();
1308 let (_dir, root, sessions) = history();
1309 std::fs::write(
1310 sessions.join("session.jsonl"),
1311 format!(
1312 "CONFIDENTIAL\n{}\n",
1313 assistant_line("We decided to keep the marked sentence")
1314 ),
1315 )
1316 .expect("transcript");
1317
1318 let _policy = block_confidential();
1319 let result = claude_code::import_from_root(&root);
1320 assert!(result.facts.is_empty(), "{:?}", decisions(&result));
1321 assert_eq!(result.sources_refused, 1);
1322 assert_eq!(result.facts_skipped, 0, "the file was refused as a whole");
1323 assert!(result.errors.is_empty(), "{:?}", result.errors);
1324 }
1325
1326 #[test]
1330 fn a_database_at_a_refused_path_is_not_opened() {
1331 let _data = crate::core::data_dir::isolated_data_dir();
1332 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1333 let (_dir, root, _sessions) = history();
1334 let secret_dir = root.join(".aws");
1335 std::fs::create_dir_all(&secret_dir).expect("secret-like dir");
1336 let database = secret_dir.join("history.sqlite");
1337 codex_database(
1338 &database,
1339 &[r#"{"role":"assistant","content":"We decided to use a bounded cache"}"#],
1340 );
1341
1342 crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", "enforce");
1343 let decision = admit_history_database(&root, &database);
1344 let result = codex::import_from_root(&root);
1345 crate::test_env::remove_var("LEAN_CTX_IO_BOUNDARY_MODE");
1346
1347 assert_eq!(decision, Err(SourceRefusal::Withheld));
1348 assert_eq!(result.sources_refused, 1);
1349 assert_eq!(result.facts_skipped, 0);
1350 assert!(result.facts.is_empty(), "{:?}", decisions(&result));
1351
1352 crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", "warn");
1356 let warned = admit_history_database(&root, &database);
1357 crate::test_env::remove_var("LEAN_CTX_IO_BOUNDARY_MODE");
1358 assert!(warned.is_ok());
1359 }
1360
1361 #[test]
1370 fn a_transcript_above_the_read_cap_is_imported_in_admitted_units() {
1371 let _data = crate::core::data_dir::isolated_data_dir();
1372 let policy = crate::core::policy::load(&format!("{BLOCK_CONFIDENTIAL}pii = \"block\"\n"))
1373 .expect("policy");
1374 let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(policy));
1375 let _cap = crate::test_env::EnvVarGuard::set("LCTX_MAX_READ_BYTES", "1024");
1376 let (_dir, root, sessions) = history();
1377 let expected: Vec<String> = ('a'..='c')
1379 .flat_map(|x| ('a'..='t').map(move |y| (x, y)))
1380 .map(|(x, y)| format!("We decided to keep the unit marker é {x}{y}"))
1381 .collect();
1382 let records: Vec<String> = expected.iter().map(|text| assistant_line(text)).collect();
1383 let write = |records: &[String], end: &str| {
1384 std::fs::write(sessions.join("long.jsonl"), records.join("\n") + "\n" + end)
1385 .expect("transcript");
1386 };
1387 let width = records[0].len();
1388 let per_unit = bounded::unit_bytes() / (width + 1);
1389 assert!(records.len() > 3 * per_unit, "several units");
1390
1391 write(&records, "");
1392 let result = claude_code::import_from_root(&root);
1393 assert_eq!((result.sources_skipped, result.sources_refused), (0, 0));
1394 assert!(result.errors.is_empty(), "{:?}", result.errors);
1395 assert_eq!(decisions(&result), expected);
1396
1397 write(&records, "CONFIDENTIAL\n");
1398 let result = claude_code::import_from_root(&root);
1399 assert!(result.facts.is_empty(), "{:?}", decisions(&result));
1400 assert_eq!((result.sources_skipped, result.sources_refused), (0, 1));
1401
1402 use crate::core::context_admission::cross_line::pattern_is_single_line;
1403 assert!(pattern_is_single_line(r"EMP-\d{4}") && !pattern_is_single_line(r"left\s+right"));
1404
1405 write(&records, "");
1410 std::fs::write(sessions.join("next.jsonl"), format!("{}\n", records[0])).expect("next");
1411 bounded::FAIL_BEFORE_UNIT.with(|fault| fault.set(Some(1)));
1412 let result = claude_code::import_from_root(&root);
1413 bounded::FAIL_BEFORE_UNIT.with(|fault| fault.set(None));
1414 assert_eq!(decisions(&result), vec![expected[0].as_str()]);
1415 assert_eq!(
1416 (
1417 result.sources_skipped,
1418 result.sources_refused,
1419 result.facts_skipped
1420 ),
1421 (1, 0, 0)
1422 );
1423 assert_eq!((result.facts_extracted, result.errors.len()), (1, 0));
1424 }
1425
1426 #[cfg(unix)]
1431 #[test]
1432 fn a_database_exchanged_after_verification_is_refused() {
1433 let _data = crate::core::data_dir::isolated_data_dir();
1434 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1435 let (_dir, root, sessions) = history();
1436 let database = root.join("history.sqlite");
1437 let other = sessions.join("other.sqlite");
1438 let row = r#"{"role":"assistant","content":"We decided to keep the verified marker"}"#;
1439 codex_database(&database, &[row]);
1440 codex_database(&other, &[row]);
1441
1442 let verified = database::verify_history_database(&root, &database).expect("verified");
1443 std::fs::rename(&other, &database).expect("rename over");
1444 assert_eq!(verified.into_snapshot().err(), Some(SourceRefusal::Changed));
1445
1446 let verified = database::verify_history_database(&root, &database).expect("verified");
1447 std::fs::rename(&database, &other).expect("move away");
1448 std::os::unix::fs::symlink(&other, &database).expect("link in its place");
1449 assert_eq!(verified.into_snapshot().err(), Some(SourceRefusal::Changed));
1450 }
1451}