Skip to main content

lean_ctx/core/
consolidation_engine.rs

1//! Canonical session→knowledge consolidation (#995 Phase 4).
2//!
3//! One session-import core (`import_session_into`) and one option set
4//! ([`ConsolidateOptions`]) back every consolidation driver — the CLI/MCP
5//! `consolidate`, the post-dispatch scheduled pass, startup auto-consolidate and
6//! the cognition loop — so promotion budgets, fact keys, confidences and the
7//! lossless capacity reclaim stay identical regardless of who triggers a run.
8//!
9//! The full, locked orchestrator (import + history + lifecycle + per-store
10//! reclaim + report) lives in
11//! `ctx_knowledge::consolidate_project_knowledge_with`; this module owns the
12//! shared import primitive plus the thin `scheduled` wrapper the background
13//! drivers call.
14
15use chrono::{DateTime, Utc};
16
17use crate::core::archive::bindings::{self, Item};
18use crate::core::knowledge::{KnowledgeFact, ProjectKnowledge};
19use crate::core::memory_policy::MemoryPolicy;
20use crate::core::session::{Finding, SessionState};
21
22/// Promotion budgets for the scheduled (post-dispatch / cognition) pass.
23#[derive(Debug, Clone, Copy)]
24pub struct ConsolidationBudgets {
25    pub max_decisions: usize,
26    pub max_findings: usize,
27}
28
29impl Default for ConsolidationBudgets {
30    fn default() -> Self {
31        Self {
32            max_decisions: 5,
33            max_findings: 8,
34        }
35    }
36}
37
38/// Leaner outcome kept for the scheduled callers (post_dispatch / tool_lifecycle)
39/// that only need the promotion + lifecycle headline, not the full report.
40#[derive(Debug, Clone)]
41pub struct ConsolidationOutcome {
42    pub promoted: u32,
43    pub promoted_decisions: u32,
44    pub promoted_findings: u32,
45    pub lifecycle_archived: usize,
46    pub lifecycle_remaining: usize,
47}
48
49/// How a consolidation run imports the session and reclaims capacity. One option
50/// set per driver — see the constructors. Replaces the four divergent, copy-pasted
51/// import loops (each with subtly different keys, caps and confidences).
52#[derive(Debug, Clone)]
53pub struct ConsolidateOptions {
54    /// Promote the latest session's findings/decisions into knowledge.
55    pub import_session: bool,
56    /// Cap promoted decisions (`None` = all).
57    pub decision_budget: Option<usize>,
58    /// Cap promoted findings (`None` = all).
59    pub finding_budget: Option<usize>,
60    /// Skip findings below this salience score (`None` = import all).
61    pub finding_salience_floor: Option<u32>,
62    /// Confidence assigned to imported decisions.
63    pub decision_confidence: f32,
64    /// Confidence assigned to imported findings.
65    pub finding_confidence: f32,
66    /// Import only items newer than the session watermark and advance it after
67    /// (incremental auto-consolidate).
68    pub incremental: bool,
69    /// Run the fact lifecycle (decay / dedup / quality + capacity) after import.
70    pub run_lifecycle: bool,
71    /// Run the lossless capacity reclaim for history / procedures / patterns.
72    pub reclaim_stores: bool,
73    /// Emit a `KnowledgeUpdate` event after a successful (non-dry) run.
74    pub emit_event: bool,
75    /// Compute the report without mutating knowledge, archives or the session.
76    pub dry_run: bool,
77    /// Optional private selection for bounded scheduled imports; never used with
78    /// a watermark, which would otherwise skip unselected session entries.
79    pub private_curation: bool,
80}
81
82impl ConsolidateOptions {
83    /// Explicit CLI / MCP `consolidate`: import everything, full lifecycle and a
84    /// lossless reclaim of every store. Applies a salience floor to keep
85    /// low-signal auto-findings ("Read file.txt") out of knowledge.
86    pub fn manual() -> Self {
87        Self {
88            import_session: true,
89            decision_budget: None,
90            finding_budget: None,
91            finding_salience_floor: Some(45),
92            decision_confidence: 0.85,
93            finding_confidence: 0.7,
94            incremental: false,
95            run_lifecycle: true,
96            reclaim_stores: true,
97            emit_event: false,
98            dry_run: false,
99            private_curation: false,
100        }
101    }
102
103    /// Scheduled background pass (post-dispatch / cognition): salience-gated,
104    /// budgeted, runs the fact lifecycle and emits an event.
105    pub fn scheduled(b: ConsolidationBudgets) -> Self {
106        Self {
107            import_session: true,
108            decision_budget: Some(b.max_decisions),
109            finding_budget: Some(b.max_findings),
110            finding_salience_floor: Some(45),
111            decision_confidence: 0.9,
112            finding_confidence: 0.75,
113            incremental: false,
114            run_lifecycle: true,
115            reclaim_stores: false,
116            emit_event: true,
117            dry_run: false,
118            private_curation: true,
119        }
120    }
121
122    /// Startup auto-consolidate: incremental (watermark) import only, no lifecycle.
123    pub fn incremental_auto() -> Self {
124        Self {
125            import_session: true,
126            decision_budget: None,
127            finding_budget: None,
128            finding_salience_floor: Some(45),
129            decision_confidence: 0.85,
130            finding_confidence: 0.7,
131            incremental: true,
132            run_lifecycle: false,
133            reclaim_stores: false,
134            emit_event: false,
135            dry_run: false,
136            private_curation: false,
137        }
138    }
139
140    /// Same plan, but preview-only: no writes to knowledge, archives or session.
141    #[must_use]
142    pub fn into_dry_run(mut self) -> Self {
143        self.dry_run = true;
144        self
145    }
146}
147
148/// Counts of items promoted by a single `import_session_into` call.
149#[derive(Debug, Default, Clone, Copy)]
150pub struct ImportCounts {
151    pub decisions: usize,
152    pub findings: usize,
153    pub curation: Option<&'static str>,
154}
155
156impl ImportCounts {
157    pub fn total(self) -> usize {
158        self.decisions + self.findings
159    }
160}
161
162/// The single session→knowledge import. Operates on an already-locked
163/// `knowledge` (no nested knowledge lock), so both the locked orchestrator and the
164/// cognition loop — which holds the knowledge lock across all its steps — share
165/// one implementation. `watermark` (incremental mode) imports only newer items.
166pub fn import_session_into(
167    knowledge: &mut ProjectKnowledge,
168    session: &SessionState,
169    opts: &ConsolidateOptions,
170    policy: &MemoryPolicy,
171    watermark: Option<DateTime<Utc>>,
172) -> ImportCounts {
173    let is_new = |ts: DateTime<Utc>| watermark.is_none_or(|w| ts > w);
174
175    let mut decisions: Vec<&crate::core::session::Decision> = session
176        .decisions
177        .iter()
178        .filter(|d| is_new(d.timestamp))
179        .collect();
180    decisions.sort_by_key(|d| std::cmp::Reverse(d.timestamp));
181    let mut findings: Vec<&Finding> = session
182        .findings
183        .iter()
184        .filter(|f| is_new(f.timestamp))
185        .collect();
186    findings.sort_by_key(|f| std::cmp::Reverse(f.timestamp));
187    let curation = if opts.private_curation && !opts.incremental && watermark.is_none() {
188        curate(knowledge, &mut decisions, &mut findings, opts)
189    } else {
190        None
191    };
192    if let Some(n) = opts.decision_budget {
193        decisions.truncate(n);
194    }
195    let mut decision_count = 0;
196    for d in &decisions {
197        let key = slug_key(&d.summary, 50);
198        knowledge.remember(
199            "decision",
200            &key,
201            &d.summary,
202            &session.id,
203            opts.decision_confidence,
204            policy,
205        );
206        decision_count += 1;
207    }
208
209    let mut finding_count = 0;
210    for f in &findings {
211        if opts.finding_budget.is_some_and(|n| finding_count >= n) {
212            break;
213        }
214        if crate::core::auto_findings::is_activity_record(f.summary.trim()) {
215            continue;
216        }
217        if let Some(floor) = opts.finding_salience_floor
218            && crate::core::memory_salience::text_salience(&f.summary) < floor
219        {
220            continue;
221        }
222        let key = finding_key(f);
223        // The fact's value is the finding's summary: it keeps the finding's
224        // source binding, and is not stored when that binding does not hold.
225        let stored = store_derived(
226            knowledge,
227            &[finding_item(session, f)],
228            session.project_root.as_deref(),
229            ["finding", &key, &f.summary],
230            opts.dry_run,
231            |knowledge| {
232                knowledge.remember(
233                    "finding",
234                    &key,
235                    &f.summary,
236                    &session.id,
237                    opts.finding_confidence,
238                    policy,
239                );
240            },
241        );
242        if stored {
243            finding_count += 1;
244        }
245    }
246
247    if opts.import_session {
248        store_session_facts(knowledge, session, opts.dry_run);
249    }
250
251    ImportCounts {
252        decisions: decision_count,
253        findings: finding_count,
254        curation,
255    }
256}
257
258fn finding_item<'a>(session: &'a SessionState, finding: &'a Finding) -> (Item<'a>, &'a str) {
259    let item = Item::SessionFinding {
260        session: &session.id,
261        file: finding.file.as_deref(),
262    };
263    (item, finding.summary.as_str())
264}
265
266/// Store the facts a session derives (`SessionState::derived_facts`). A fact
267/// built from a finding keeps that finding's source binding ([`store_derived`]);
268/// a decision and a touched-file record have none, and are stored as before.
269/// `dry_run`: the store is a throwaway copy, no binding is written.
270pub(crate) fn store_session_facts(
271    knowledge: &mut ProjectKnowledge,
272    session: &SessionState,
273    dry_run: bool,
274) {
275    for (fact, finding) in session.derived_facts() {
276        let Some(finding) = finding else {
277            knowledge.add_fact(fact);
278            continue;
279        };
280        let (category, key, value) = (fact.category.clone(), fact.key.clone(), fact.value.clone());
281        store_derived(
282            knowledge,
283            &[finding_item(session, finding)],
284            session.project_root.as_deref(),
285            [&category, &key, &value],
286            dry_run,
287            |knowledge| {
288                knowledge.add_fact(fact);
289            },
290        );
291    }
292}
293
294/// Store a fact (`store`) whose `text` is DERIVED from other stored items —
295/// `origins`, each with the text its store keeps — and carry their source
296/// bindings over to it (`archive::bindings::carry`). Returns whether the fact
297/// was stored (in a dry run: would be).
298///
299/// - every origin has a binding that holds now: the fact is stored and bound
300///   to the same files, read again now. Its recall is then re-checked against
301///   those files like a fact remembered with `sources`;
302/// - an origin has no binding: the fact is stored originless, as before;
303/// - while protection is active, an origin that is bound and not served now,
304///   a source that no longer admits, or a text the store would not keep
305///   byte-identical: NOTHING is stored. An unbound copy of text whose source
306///   is withheld would be delivered where the origin is not.
307///
308/// A binding is written only after the store kept exactly `text` under
309/// `category`/`key`; if the register then refuses the write, the fact is
310/// taken out again. Without protection nothing is refused.
311pub(crate) fn store_derived(
312    knowledge: &mut ProjectKnowledge,
313    origins: &[(Item<'_>, &str)],
314    reader_project: Option<&str>,
315    fields: [&str; 3],
316    dry_run: bool,
317    store: impl FnOnce(&mut ProjectKnowledge),
318) -> bool {
319    let [category, key, text] = fields;
320    let root = knowledge.project_root.clone();
321    let fact = Item::KnowledgeFact {
322        project: &root,
323        category,
324        key,
325    };
326    let carried = bindings::carry(&fact, text, origins, reader_project);
327    store_carried(knowledge, carried, fields, dry_run, store)
328}
329
330/// [`store_derived`] with the carry already prepared by the caller, for a
331/// fact whose origin's binding is not in the register (`bindings::carry_from`:
332/// a fact restored from a handoff ledger). `carried` must be the carry of
333/// exactly `fields` for the fact item of this store's root. The rules are
334/// those of [`store_derived`]: `Err` stores nothing, `Ok(None)` stores the
335/// fact originless, `Ok(Some(_))` stores it and then writes its binding.
336pub(crate) fn store_carried(
337    knowledge: &mut ProjectKnowledge,
338    carried: Result<Option<bindings::Carried>, crate::core::context_admission::carrier::Withheld>,
339    [category, key, text]: [&str; 3],
340    dry_run: bool,
341    store: impl FnOnce(&mut ProjectKnowledge),
342) -> bool {
343    let enforced = crate::core::context_admission::stored::source_authority_required();
344    let root = knowledge.project_root.clone();
345    let fact = Item::KnowledgeFact {
346        project: &root,
347        category,
348        key,
349    };
350    let Ok(carried) = carried else {
351        return false;
352    };
353    let verbatim = carried.is_some() && knowledge.admits_verbatim([category, key, text]);
354    if enforced && carried.is_some() && !verbatim {
355        return false;
356    }
357    store(knowledge);
358    let kept = |stored: &KnowledgeFact| {
359        stored.is_current()
360            && stored.category == category
361            && stored.key == key
362            && stored.value == text
363    };
364    // AP01 §4: a machine-derived fact that carries source bindings or names
365    // files is about code at a revision (`content`), never a convention.
366    let names_files = carried.is_some()
367        || [key, text]
368            .iter()
369            .any(|part| !crate::core::content_chunk::extract_file_references(part).is_empty());
370    if names_files {
371        for stored in knowledge.facts.iter_mut().filter(|stored| kept(stored)) {
372            stored
373                .validity
374                .get_or_insert(crate::core::knowledge::FactValidity::Content);
375        }
376    }
377    let Some(carried) = carried.filter(|_| verbatim && !dry_run) else {
378        return true;
379    };
380    if !knowledge.facts.iter().any(kept) || carried.commit(&fact, text) || !enforced {
381        return true;
382    }
383    knowledge.facts.retain(|stored| !kept(stored));
384    knowledge.rebuild_index();
385    false
386}
387
388/// Build a bounded metadata projection before any import mutates knowledge.
389/// Failure keeps the original OSS input lists; selected views never replace or
390/// advance the original session, and structured session facts keep their path.
391fn curate(
392    knowledge: &ProjectKnowledge,
393    decisions: &mut Vec<&crate::core::session::Decision>,
394    findings: &mut Vec<&Finding>,
395    opts: &ConsolidateOptions,
396) -> Option<&'static str> {
397    use crate::core::intelligence_runtime::memory_curation::{Candidate, select};
398    let known = |category: &str, key: &str, value: &str| {
399        knowledge.facts.iter().any(|fact| {
400            fact.is_current() && fact.category == category && fact.key == key && fact.value == value
401        })
402    };
403    let now = Utc::now();
404    let age = |timestamp: DateTime<Utc>| (now - timestamp).num_days().clamp(0, 36500) as u16;
405    let mut candidates = Vec::with_capacity(128);
406    for d in decisions.iter().take(64) {
407        candidates.push(Candidate {
408            candidate_id: candidates.len(),
409            decision: true,
410            salience: crate::core::memory_salience::text_salience(&d.summary).min(100) as u8,
411            known: known("decision", &slug_key(&d.summary, 50), &d.summary),
412            age_days: age(d.timestamp),
413        });
414    }
415    let decision_count = candidates.len();
416    for f in findings.iter().take(64) {
417        candidates.push(Candidate {
418            candidate_id: candidates.len(),
419            decision: false,
420            salience: crate::core::memory_salience::text_salience(&f.summary).min(100) as u8,
421            known: known("finding", &finding_key(f), &f.summary),
422            age_days: age(f.timestamp),
423        });
424    }
425    let Ok(selected) = select(
426        &candidates,
427        opts.decision_budget.unwrap_or(32),
428        opts.finding_budget.unwrap_or(32),
429    )?
430    else {
431        return Some("unavailable; standard local consolidation used");
432    };
433    *decisions = decisions
434        .iter()
435        .take(64)
436        .enumerate()
437        .filter(|(index, _)| selected.binary_search(index).is_ok())
438        .map(|(_, item)| *item)
439        .collect();
440    *findings = findings
441        .iter()
442        .take(64)
443        .enumerate()
444        .filter(|(index, _)| selected.binary_search(&(decision_count + index)).is_ok())
445        .map(|(_, item)| *item)
446        .collect();
447    Some("novel_salience_v1; original session retained")
448}
449
450/// Stable knowledge key for a session finding: `file[:line]` when located, else a
451/// content slug. Content-based (never index-based), so re-imports upsert the same
452/// fact and the output stays deterministic across runs (#498).
453pub fn finding_key(f: &Finding) -> String {
454    match (&f.file, f.line) {
455        (Some(file), Some(line)) => format!("{file}:{line}"),
456        (Some(file), None) => file.clone(),
457        (None, _) => format!("finding-{}", slug_key(&f.summary, 36)),
458    }
459}
460
461/// Scheduled background consolidation. Thin wrapper over the canonical
462/// orchestrator with [`ConsolidateOptions::scheduled`]; kept for the
463/// post-dispatch / SDK callers and their `ConsolidationOutcome`. Imports only
464/// the caller's own session (`session::caller`); without a caller only
465/// project facts are consolidated — never the project's latest saved
466/// session, which may be another agent's (I07/S03).
467pub fn consolidate_latest(
468    project_root: &str,
469    budgets: ConsolidationBudgets,
470) -> Result<ConsolidationOutcome, String> {
471    let opts = ConsolidateOptions::scheduled(budgets);
472    let report =
473        crate::tools::ctx_knowledge::consolidate_project_knowledge_with(project_root, &opts)?;
474
475    Ok(ConsolidationOutcome {
476        promoted: (report.imported_decisions + report.imported_findings) as u32,
477        promoted_decisions: report.imported_decisions as u32,
478        promoted_findings: report.imported_findings as u32,
479        lifecycle_archived: report.lifecycle.archived_count,
480        lifecycle_remaining: report.lifecycle.remaining_facts,
481    })
482}
483
484/// Deterministic, filesystem-safe slug for a fact key: lowercase alphanumerics,
485/// single dashes for separators, trimmed, capped at `max` bytes.
486pub fn slug_key(s: &str, max: usize) -> String {
487    let mut out = String::new();
488    for ch in s.chars() {
489        if out.len() >= max {
490            break;
491        }
492        if ch.is_ascii_alphanumeric() {
493            out.push(ch.to_ascii_lowercase());
494        } else if (ch.is_whitespace() || ch == '-' || ch == '_')
495            && !out.ends_with('-')
496            && !out.is_empty()
497        {
498            out.push('-');
499        }
500    }
501    out.trim_matches('-').to_string()
502}
503
504#[cfg(test)]
505pub mod tests {
506    use super::*;
507
508    #[test]
509    fn consolidate_promotes_decisions_and_salient_findings_only() {
510        let _lock = crate::core::data_dir::test_env_lock();
511        let tmp = tempfile::tempdir().expect("tempdir");
512        crate::test_env::set_var(
513            "LEAN_CTX_DATA_DIR",
514            tmp.path().to_string_lossy().to_string(),
515        );
516
517        let project_root = tmp.path().join("proj");
518        std::fs::create_dir_all(&project_root).expect("mkdir");
519        let project_root_str = project_root.to_string_lossy().to_string();
520
521        let mut session = SessionState::new();
522        session.project_root = Some(project_root_str.clone());
523        session.add_decision("Use archive-only memory lifecycle", None);
524        session.add_finding(None, None, "panic: index out of bounds");
525        session.add_finding(None, None, "just a note");
526        session.save().expect("save session");
527        let budgets = ConsolidationBudgets {
528            max_decisions: 5,
529            max_findings: 5,
530        };
531
532        // I07/S03: a run without a caller (background, SDK, CLI) promotes
533        // nothing from the saved session — it may be another agent's. It
534        // imported the project's latest session.
535        let out = consolidate_latest(&project_root_str, budgets).expect("consolidate");
536        assert_eq!(out.promoted, 0);
537        let leaked = ProjectKnowledge::load(&project_root_str)
538            .is_some_and(|k| k.facts.iter().any(|f| f.value.contains("archive-only")));
539        assert!(
540            !leaked,
541            "another agent's decision reached project knowledge"
542        );
543
544        // The session's own agent consolidates it.
545        let own = std::sync::Arc::new(tokio::sync::RwLock::new(session));
546        let out = crate::core::session::caller::scope(Some(own), || {
547            consolidate_latest(&project_root_str, budgets)
548        })
549        .expect("consolidate");
550        assert!(out.promoted_decisions >= 1);
551        assert!(out.promoted_findings >= 1);
552
553        let k = ProjectKnowledge::load(&project_root_str).expect("knowledge saved");
554        let active = k.facts.iter().filter(|f| f.is_current()).count();
555        assert!(active >= 2, "expected promoted facts");
556
557        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
558    }
559
560    #[test]
561    fn finding_key_is_content_based_and_deterministic() {
562        let f1 = Finding {
563            file: Some("src/main.rs".into()),
564            line: Some(42),
565            summary: "boom".into(),
566            timestamp: Utc::now(),
567        };
568        assert_eq!(finding_key(&f1), "src/main.rs:42");
569
570        let f2 = Finding {
571            file: None,
572            line: None,
573            summary: "Race condition in cache".into(),
574            timestamp: Utc::now(),
575        };
576        // Same content → same key (idempotent re-import, no index drift).
577        assert_eq!(finding_key(&f2), finding_key(&f2));
578        assert_eq!(finding_key(&f2), "finding-race-condition-in-cache");
579    }
580
581    use crate::core::archive::delivered::LineageRefusal;
582    use crate::core::context_admission::stored::lineage_support::{
583        deliver, governed, project, reusable, scoped,
584    };
585    use crate::core::policy::runtime::TestPolicyOverride;
586
587    const BOUND: &str = "panic: the pool fails to lease";
588    const TYPED: &str = "error: the deploy fails without a token";
589
590    /// [`governed`] with `auto_capture` switched on: the store keeps a
591    /// machine-derived fact (`auto:blocker`) only then (#1802,
592    /// `knowledge::persist::machine_derived_writes_allowed`), and a
593    /// configuration FILE that does not name the key reads as `false` — the
594    /// file `governed` writes switched it off.
595    fn governed_with_auto_capture() -> crate::core::data_dir::IsolatedDataDir {
596        let data = governed();
597        let dir = crate::core::paths::config_dir_read_only().expect("isolated config dir");
598        std::fs::write(
599            dir.join("config.toml"),
600            "auto_capture = true\n\n[context_gateway]\nmode = \"governed\"\n",
601        )
602        .expect("config");
603        data
604    }
605
606    /// A session with one finding bound to `pool.rs` and one without a file.
607    fn session_with_two_findings(root: &str) -> SessionState {
608        std::fs::write(format!("{root}/pool.rs"), "pub fn lease() {}\n").expect("source");
609        let mut session = SessionState::new();
610        session.project_root = Some(root.to_owned());
611        session.add_finding_for_file(Some("pool.rs"), Some(1), BOUND);
612        session.add_finding_for_file(None, None, TYPED);
613        session
614    }
615
616    /// Import `session` into a fresh in-memory store, every finding eligible.
617    fn import(
618        root: &str,
619        session: &SessionState,
620        dry_run: bool,
621    ) -> (ProjectKnowledge, ImportCounts) {
622        let options = ConsolidateOptions {
623            finding_salience_floor: None,
624            dry_run,
625            ..ConsolidateOptions::manual()
626        };
627        scoped(root, || {
628            let mut knowledge = ProjectKnowledge::new(root);
629            let counts = import_session_into(
630                &mut knowledge,
631                session,
632                &options,
633                &MemoryPolicy::default(),
634                None,
635            );
636            (knowledge, counts)
637        })
638    }
639
640    fn derived(knowledge: &ProjectKnowledge, category: &str, text: &str) -> Option<KnowledgeFact> {
641        knowledge
642            .facts
643            .iter()
644            .find(|fact| {
645                fact.is_current() && fact.category == category && fact.value.contains(text)
646            })
647            .cloned()
648    }
649
650    /// Deliver one stored fact the way every knowledge renderer serves it.
651    fn recall(root: &str, fact: &KnowledgeFact) -> (String, usize) {
652        deliver(root, || {
653            let item = Item::KnowledgeFact {
654                project: root,
655                category: &fact.category,
656                key: &fact.key,
657            };
658            match bindings::serve(&item, &fact.value, Some(root)) {
659                Ok(()) => format!("[{}] {}", fact.category, fact.value),
660                Err(withheld) => withheld.notice(),
661            }
662        })
663    }
664
665    /// Both facts an import derives from a finding — the `finding` fact and
666    /// the `auto:blocker` fact — are bound to the finding's file: their
667    /// recall is registered and they are withheld with the file. A finding
668    /// without a binding derives originless facts. A finding that is not
669    /// served any more derives nothing.
670    #[test]
671    fn a_fact_derived_from_a_finding_keeps_the_binding_of_that_finding() {
672        let _data = governed_with_auto_capture();
673        let _community = TestPolicyOverride::set(None);
674        let (_directory, root) = project();
675        let session = session_with_two_findings(&root);
676
677        let (knowledge, counts) = import(&root, &session, false);
678        assert_eq!(counts.findings, 2);
679        let mut bound_facts = Vec::new();
680        for category in ["finding", "auto:blocker"] {
681            let bound = derived(&knowledge, category, BOUND).expect(category);
682            let (reply, recorded) = recall(&root, &bound);
683            assert!(reply.contains(BOUND), "{reply}");
684            assert_eq!(recorded, 1, "{category}: bound to pool.rs");
685            assert_eq!(reusable(&root, &reply), Ok(()));
686            bound_facts.push((bound, reply));
687
688            let typed = derived(&knowledge, category, TYPED).expect(category);
689            let (reply, recorded) = recall(&root, &typed);
690            assert!(reply.contains(TYPED), "{reply}");
691            assert_eq!(recorded, 0, "{category}: no binding to carry");
692            assert_eq!(reusable(&root, &reply), Err(LineageRefusal::Unknown));
693        }
694
695        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
696        for (fact, reply) in &bound_facts {
697            assert_eq!(
698                reusable(&root, reply),
699                Err(LineageRefusal::SourceNoLongerAdmitted)
700            );
701            let (withheld, recorded) = recall(&root, fact);
702            assert!(!withheld.contains(BOUND), "{withheld}");
703            assert_eq!(recorded, 0);
704        }
705        let (knowledge, counts) = import(&root, &session, false);
706        assert_eq!(
707            counts.findings, 1,
708            "the finding that is not served is not imported"
709        );
710        for category in ["finding", "auto:blocker"] {
711            assert!(derived(&knowledge, category, BOUND).is_none(), "{category}");
712            assert!(derived(&knowledge, category, TYPED).is_some(), "{category}");
713        }
714    }
715
716    /// A preview imports into a throwaway copy and writes no binding.
717    #[test]
718    fn a_dry_run_import_writes_no_binding() {
719        let _data = governed_with_auto_capture();
720        let _community = TestPolicyOverride::set(None);
721        let (_directory, root) = project();
722        let session = session_with_two_findings(&root);
723        let (knowledge, counts) = import(&root, &session, true);
724        assert_eq!(counts.findings, 2);
725        let previewed = derived(&knowledge, "auto:blocker", BOUND).expect("previewed");
726        assert_eq!(
727            recall(&root, &previewed).1,
728            0,
729            "no register entry was written"
730        );
731    }
732
733    /// Developer mode: nothing is refused. A finding whose file is gone still
734    /// derives its facts, as before.
735    #[test]
736    fn an_import_in_developer_mode_refuses_nothing() {
737        let _data = crate::core::data_dir::isolated_data_dir();
738        // `auto_capture` is opt-in; machine-derived facts need it (#1802).
739        let config = crate::core::paths::config_dir_read_only().expect("isolated config dir");
740        std::fs::create_dir_all(&config).expect("config dir");
741        std::fs::write(config.join("config.toml"), "auto_capture = true\n").expect("config");
742        let _community = TestPolicyOverride::set(None);
743        let (_directory, root) = project();
744        let session = session_with_two_findings(&root);
745        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
746        let (knowledge, counts) = import(&root, &session, false);
747        assert_eq!(counts.findings, 2);
748        for category in ["finding", "auto:blocker"] {
749            assert!(derived(&knowledge, category, BOUND).is_some(), "{category}");
750        }
751    }
752}