Skip to main content

lean_ctx_ext/core/import/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Import facts from local AI coding-session histories, and from the
3//! project's own instruction files, documentation and git history (K1).
4
5mod 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    /// The project's instruction files and `docs/` ([`markdown`]).
34    Docs,
35    /// The project's local git history ([`git_history`]).
36    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    /// Facts remain available to the CLI until it either persists or displays them.
60    pub facts: Vec<KnowledgeFact>,
61    /// Facts that were found but not kept: admission withholds their value
62    /// or permits it for a reader only (E3). A count — the values are gone.
63    pub facts_skipped: usize,
64    /// History sources that were found but not read to the end: above the
65    /// total cap of their kind, holding one record above the per-record
66    /// bound, or not readable. Never read in part.
67    pub sources_skipped: usize,
68    /// History sources that were not opened or not used: outside every
69    /// named root, withheld by a path rule, the policy or the gateway, or
70    /// changed between their verification and the read.
71    pub sources_refused: usize,
72    /// What a repository-source run read (`import docs`): facts of a file
73    /// it read that were not found again lost their section.
74    pub repo_scope: Option<RepoScope>,
75}
76
77/// The files a docs import read, relative to the project root, and whether
78/// it covered the whole default set (then a file that is gone lost all its
79/// facts).
80#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct RepoScope {
82    pub files: Vec<String>,
83    pub whole: bool,
84}
85
86/// Why a history source (a transcript file, a history database) was not
87/// read. Typed and content-free: no path, no byte of the source.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum SourceRefusal {
90    /// It does not resolve inside any named root (symlinks resolved).
91    OutsideRoot,
92    /// A path rule, the project policy or the gateway withholds it, or it
93    /// is delivered for a reader only and may not feed a store (E3).
94    Withheld,
95    /// It is larger than the total cap of its kind
96    /// (`bounded::MAX_TRANSCRIPT_BYTES`, `database::MAX_HISTORY_DATABASE_BYTES`;
97    /// the read cap for a single JSON document, which is one record). A
98    /// source is never read in part.
99    TooLarge,
100    /// One record of a transcript is larger than the per-record bound (the
101    /// read cap). A record is never cut and never passed uninspected, so the
102    /// transcript is not imported.
103    RecordTooLarge,
104    /// A transcript above the read cap cannot be admitted piece by piece
105    /// without being judged more weakly than as a whole: a rule that is
106    /// active now can match across lines without a bound (a policy-pack or
107    /// configured pattern not proven single-line, a semantic detector), or
108    /// a piece ends inside such a match of a built-in rule. It is not read —
109    /// as it was not before transcripts above the cap were read at all.
110    UnitAdmissionUnsupported,
111    /// One transcript or database yields more distinct facts than may be held
112    /// pending until it is read to its end (`staging::MAX_PENDING_BYTES`). It
113    /// is not imported in part.
114    TooManyFacts,
115    /// It is no longer the file that was verified, or it was written while
116    /// it was read: exchanged at its path, or changed in size or time.
117    Changed,
118    /// It cannot be read as text (missing, binary, I/O error).
119    Unreadable,
120    /// A verified database that the engine cannot open, or whose rows
121    /// cannot be stepped or decoded to their end. It is not imported in part.
122    DatabaseUnreadable,
123    /// A database without the tables and columns its importer reads.
124    UnsupportedSchema,
125}
126// The fixed sentence of each refusal (`Display`) lives in `staging`.
127
128/// A history source that resolves inside a named root: both paths canonical.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub(crate) struct HistorySource {
131    pub root: PathBuf,
132    pub path: PathBuf,
133}
134
135/// Resolve a history source inside a NAMED root — the one rule for every
136/// importer (Claude Code, Codex, Cursor, OpenCode; transcripts and
137/// databases alike).
138///
139/// The named roots are the request's project, when one is bound, and
140/// `history_root`: the directory the importer was started for. In product
141/// code that is a fixed location under the home or platform data directory
142/// (`~/.claude/projects`, `~/.codex`, `~/.cursor/projects`,
143/// `<data dir>/opencode`), never caller input. No authority is derived from
144/// `path` itself — not its directory, not a project found above it. `path`
145/// is accepted only if, with every symlink resolved, it lies inside one of
146/// the named roots; anything else is [`SourceRefusal::OutsideRoot`] and is
147/// not opened.
148///
149/// This is root containment and nothing more. It does not decide whether
150/// the path may be read (the path jail and secret-path rule do: the rooted
151/// admitted reader for a transcript, [`admit_history_database`] for a
152/// database) and it says nothing about content (the reader's admission of
153/// the file, [`AdmittedValue::admit`] for a database value).
154pub(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
170/// The path-and-policy decision for a history DATABASE, made before any
171/// `Connection::open*`: the same decision a file read gets before its file
172/// is opened (`core::io_boundary::jail_and_check_path`, the call the rooted
173/// admitted reader makes first), under the named root the path resolved in.
174///
175/// It decides on the PATH: the path jail (containment under the root or an
176/// allow-listed path), the protected-store rule, and the secret-like-path
177/// rule of the active role (refused in boundary mode `enforce`). It cannot
178/// classify content it has not read — the values that leave the database
179/// are admitted one by one ([`AdmittedValue::admit`]). Root containment
180/// alone ([`resolve_history_source`]) is NOT this decision.
181///
182/// A decision on a path does not bind the file that is opened later. The
183/// importers therefore never open the path this returns: they go through
184/// [`database::snapshot_history_database`], which makes this decision, opens
185/// the file once, checks it on its descriptor and reads from that descriptor.
186pub(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/// Why an original value yields nothing. Content-free.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub(crate) enum ValueRefusal {
199    /// The project policy or the gateway withholds the value.
200    Withheld,
201    /// It is delivered for a reader only (restricted, E3): nothing derived
202    /// from it may be stored — a clean-looking part of it included.
203    NotStorable,
204}
205
206/// An ORIGINAL value of a history source after admission — the verdict that
207/// travels with every derivation (G01: admission before selection).
208///
209/// Selecting a snippet can cut a classification marker or a banner away, so
210/// the decision is made on the whole original and inherited by whatever is
211/// taken from it. This type is that inheritance: the fact builder
212/// ([`process_admitted`]) and the selectors in front of it take an
213/// `AdmittedValue` and nothing else, and one exists only
214///
215/// - for a database column value that [`Self::admit`] admitted as a whole:
216///   withheld or not storable → no `AdmittedValue`, so nothing is derived
217///   and nothing stored; masked → the value held here IS the masked one;
218/// - for a value parsed from the text of a transcript the rooted admitted
219///   reader delivered as storable ([`Self::of_admitted_source`]);
220/// - for a value derived from one of these ([`Self::derive`]).
221///
222/// The admission of the derived fact in `push_fact` stays as a second
223/// check. It can only refuse; it never upgrades this verdict.
224#[derive(Debug, Clone)]
225pub(crate) struct AdmittedValue(Value);
226
227impl AdmittedValue {
228    /// Admit one original column value as a whole.
229    ///
230    /// The admitted unit is the VALUE: every decoded text leaf of it — each
231    /// object key, each string, each number in its JSON spelling — in
232    /// document order, one per line, as ONE text through the admission a
233    /// carrier text gets (project policy on the original, then the gateway;
234    /// classification, storability). A marker lies inside one leaf, and a
235    /// leaf is never divided: leaves are only joined, each starting its own
236    /// line, so a marker cannot be split across units and a marker in any
237    /// leaf decides for the whole value.
238    ///
239    /// When admission masks something, the strings are masked one by one in
240    /// place (a key or a number cannot be masked: that refuses the value),
241    /// and the masked value must then pass as a whole unchanged — otherwise
242    /// it is refused. Derivation never sees the raw original.
243    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    /// A value parsed from text the rooted admitted reader delivered as
261    /// storable: the whole file was admitted before it was parsed, and
262    /// `read_transcript` hands out nothing else.
263    fn of_admitted_source(value: Value) -> Self {
264        Self(value)
265    }
266
267    /// A value selected or rebuilt from this one. It inherits the verdict:
268    /// the receiver is the witness that an admitted original exists.
269    #[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
279/// The admitted form of `text` when it may feed a store, under `rules`.
280fn 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/// Test-only: admit one original value under the rules configured now. A
295/// database reader counts into its pending set (`staging::Pending::admit`).
296#[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    /// Count a source that was not read. Nothing about it is reported
320    /// beyond the count — no path, no reason text with content.
321    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
341/// lean-ctx's own data directory: where an import keeps its private scratch
342/// files (the spool of a transcript read in units, the snapshot of a history
343/// database). Never a directory of the history that is being read.
344fn 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
350/// One transcript, at most the read cap, as text that may feed a derived
351/// store.
352///
353/// The file is resolved inside a named root ([`resolve_history_source`]) and
354/// then read through the rooted admitted reader under that root — path jail,
355/// secret-path rule, project policy and gateway decided on the original. A
356/// transcript above the read cap is [`SourceRefusal::TooLarge`] here and
357/// never read in part ([`for_each_transcript_line`] reads it in admitted
358/// units instead); one that is delivered but restricted or incompletely
359/// decoded feeds no store (E3). The gateway rules are those of `gateway`, the
360/// ONE snapshot of this source.
361fn 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
385/// Hand every line of one JSONL transcript — with its 1-based number — to
386/// `each`, after admission and never before.
387///
388/// Up to the read cap the file is admitted as ONE text ([`read_transcript`]).
389/// Above it, it is admitted in units of complete records ([`bounded::admit`]):
390/// every unit passes the same admission on its original bytes, and `each`
391/// sees the first line only after the last unit was admitted. A refusal is a
392/// refusal of the whole source: on `Err` the caller takes over nothing of it
393/// (above the cap `each` may have seen lines before a late error).
394///
395/// Above the cap the whole read runs inside ONE source view ([`pinned`]).
396fn 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
425/// Run the read of one source in admitted units under ONE policy snapshot.
426///
427/// `policy::runtime::with_project_source_view` pins the pack and the role
428/// for the whole operation — every `policy::runtime::active()` inside it,
429/// the unit-safety inspection as much as each admission, is that one
430/// snapshot — and compares the pack fingerprint and the role fingerprint
431/// again when the operation ends. The gateway rules are one snapshot held by
432/// the unit reader and compared when the last unit was read. A change of
433/// either, or a policy that cannot be resolved, withholds the source; `Ok`
434/// is the point immediately before its pending set is taken over.
435fn 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        // All or nothing per source, under ONE gateway snapshot (label, read,
457        // built facts): the lines fill a pending set; result, dedupe sets and
458        // counters are touched only when the source was read to its end.
459        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/// Test-only entry with the former signature: admits `value` as an original
517/// and then builds facts from it. Product code has only
518/// [`process_admitted`].
519#[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
534/// Build facts from an admitted value: select file paths, decisions and
535/// errors from it. Selection happens here, AFTER the admission of the
536/// original — the parameter type is the proof.
537fn 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    // Found and taken over at once: one parsed JSON document has no failure
545    // point after its read. Transcripts and databases go through `Pending`.
546    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
570/// The `source_session` label stored with every fact of one session:
571/// `<importer>:<name>`. `name` is a file name or a database's session id —
572/// text that lean-ctx did not choose and that is persisted with the fact. It
573/// is kept only if it passes admission for a store unchanged (E3) under
574/// `rules`, the snapshot of its source; otherwise `<importer>:unnamed-session`.
575pub(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    // Every fact is built here, whatever it was mined from (a transcript
599    // line, a database row), so this is where it is admitted for the store
600    // it is headed to (E3): a value the gateway masks is kept masked, a
601    // withheld or restricted one is not kept at all — it is counted, and
602    // nothing of it is reported. The fact carries no source binding. The
603    // rules are those of its source's ONE snapshot (`origin.rules`).
604    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
646/// One fact a repository source ([`markdown`], [`git_history`]) yields, before
647/// it is admitted for its store.
648pub(crate) struct RepoFact {
649    pub category: &'static str,
650    /// Where it comes from inside the project: `<file>#<section>/<n>` or
651    /// `git:<commit>`. Content-addressed anchors only, never a value.
652    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    /// The section (or commit) it is anchored to, when one could be captured.
658    pub anchors: Vec<crate::core::knowledge::anchors::CodeAnchor>,
659}
660
661/// Build the fact of a repository source: admitted for its store (E3) under
662/// `rules`, the one snapshot of the source, exactly as [`push_fact`] does for
663/// a history — masked stays masked, withheld or restricted is counted in
664/// `facts_skipped` and dropped. Deduplicated on `(category, value)`.
665pub(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    // The first char boundary *at or past* the cap can land one byte over it:
821    // with 2-byte characters starting at an odd offset the boundaries are
822    // 11, 13, … 499, 501, so a 500-byte cap yielded a 501-byte slice. Take the
823    // last boundary at or below the cap instead — the same idiom already used
824    // in `ctx_search` and `ctx_preload`.
825    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    /// A history root with one Claude-Code-shaped session directory, as
881    /// canonical paths (the rooted reader compares resolved paths).
882    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    /// E3, for every caller: facts were built from transcript text as it
904    /// was and only the CLI admitted them before storing. Each value is now
905    /// admitted where the fact is built — a clean value keeps its bytes, a
906    /// key-shaped value is never handed out raw.
907    #[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        // Two decisions were found: each is a fact or a counted skip.
940        assert_eq!(decisions.len() + result.facts_skipped, 2);
941        assert_eq!(result.facts_extracted, result.facts.len());
942    }
943
944    /// A value the current policy withholds or restricts is not kept: it is
945    /// counted, and neither the facts nor the errors carry anything of it.
946    #[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            // The same withheld value again: one distinct value, one count.
962            "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    /// The root rule: a transcript that resolves outside the named history
984    /// root is not read — no root is derived from where it really lives.
985    #[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        // The one rule every importer uses, decided on resolved paths, with
1018        // a typed, content-free reason.
1019        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    /// The named history roots stay usable: a hidden directory under the
1049    /// home directory is a root the rooted admitted reader accepts, and the
1050    /// `.jsonl` transcripts inside it are read. (Fixtures shaped like
1051    /// `~/.claude/projects` and `~/.codex`.)
1052    #[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    /// A transcript above the read cap whose second record is itself above
1099    /// the per-record bound is skipped whole and counted — it is never read
1100    /// in part and treated as complete, and the record is never cut: the
1101    /// typed reason is the oversized record, not the size of the file.
1102    #[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    /// A session label is persisted with every fact: a name that admission
1127    /// would change is not kept.
1128    #[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    /// A Codex-shaped history database with one table of TEXT rows.
1154    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    /// G01, the order: an original value is admitted as a WHOLE before
1165    /// anything is selected from it. A marker in one leaf decides for the
1166    /// value — the clean, importable sentence in another leaf is not a fact.
1167    #[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    /// A value the gateway masks is derived from in its MASKED form only.
1193    #[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            // Not permitted for a store at all: nothing is derived.
1208            Err(refusal) => assert!(
1209                matches!(refusal, ValueRefusal::NotStorable | ValueRefusal::Withheld),
1210                "{refusal:?}"
1211            ),
1212        }
1213    }
1214
1215    /// The same order for a Codex TEXT column: the row with a marker next to
1216    /// an importable sentence yields no fact; the clean row does.
1217    #[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        // All or nothing per database: a second database whose SECOND row
1245        // cannot be stepped (a generated column over a body that is not
1246        // JSON) adds its one skip and one fixed sentence — nothing of its
1247        // first row, no session, no counter.
1248        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    /// A key-shaped secret next to an importable sentence in a database
1272    /// column: whatever is stored comes from the masked value.
1273    #[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    /// The same order for a transcript: the rooted admitted reader admits
1303    /// the whole file before a line is parsed, so a marker in one place
1304    /// withholds the importable sentence in another.
1305    #[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    /// The path decision before a database is opened: a secret-like path
1327    /// under boundary mode `enforce` is refused like a file read would be —
1328    /// not opened, counted.
1329    #[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        // In boundary mode `warn` the same path is a readable source. The
1353        // mode is named: a role's default mode is `enforce`
1354        // (`roles::default_boundary_mode`), so "no variable" is not `warn`.
1355        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    /// A transcript above the read cap is imported: read in units of complete
1362    /// records, each unit admitted on its original bytes before a line is
1363    /// parsed. The units cover the file — every record is a fact, in order,
1364    /// multi-byte text intact — and the source rule holds across units: a
1365    /// marking in the LAST unit withholds the records of the first.
1366    ///
1367    /// A pattern that could match across lines without a bound is never
1368    /// taken for a single-line one (it would refuse unit admission).
1369    #[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        // Digit-free records of one length: the unit boundaries are known.
1378        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        // All or nothing per source: the read fails after the first unit was
1406        // parsed. Nothing of that source is taken over — no fact, no counter
1407        // but its one skip, and no dedupe state: the decision it shares with
1408        // the NEXT source is still imported from there.
1409        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    /// The database is bound to the descriptor it was verified on. A file
1427    /// exchanged at the path after the verification — renamed over, or
1428    /// replaced by a link — is refused with a typed reason: nothing is read,
1429    /// neither from the exchanged file nor from the verified one.
1430    #[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}