Skip to main content

lean_ctx_server/tools/ctx_knowledge/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx_time::UtcDateTime;
3
4#[cfg(feature = "embeddings")]
5use lean_ctx::core::embeddings::EmbeddingEngine;
6
7use lean_ctx::core::consolidation_engine::ConsolidateOptions;
8use lean_ctx::core::knowledge::ProjectKnowledge;
9use lean_ctx::core::memory_policy::MemoryPolicy;
10use lean_ctx::core::session::SessionState;
11mod changes;
12pub(crate) use changes::session_change_count;
13pub(crate) mod embeddings;
14pub(crate) use embeddings::*;
15pub mod fact_ids;
16pub mod freshness;
17mod linked;
18mod remember;
19pub use remember::*;
20mod restore;
21pub use restore::{DEFAULT_RESTORE_LIMIT, RestoreOptions, format_restore_report, run_restore};
22mod search;
23pub(crate) use search::*;
24
25mod consolidate;
26pub use consolidate::*;
27#[cfg(test)]
28mod cloud_guard_tests;
29#[cfg(test)]
30mod engine_tests;
31#[cfg(test)]
32mod recall_window_tests;
33#[cfg(test)]
34mod tests;
35
36/// Dispatches knowledge base actions (remember, recall, pattern, timeline, etc.).
37#[allow(clippy::too_many_arguments)]
38pub fn handle(
39    project_root: &str,
40    action: &str,
41    category: Option<&str>,
42    key: Option<&str>,
43    value: Option<&str>,
44    query: Option<&str>,
45    session_id: &str,
46    pattern_type: Option<&str>,
47    examples: Option<Vec<String>>,
48    confidence: Option<f32>,
49    mode: Option<&str>,
50    as_of: Option<&str>,
51) -> String {
52    match handle_outcome(
53        project_root,
54        action,
55        category,
56        key,
57        value,
58        query,
59        session_id,
60        pattern_type,
61        examples,
62        confidence,
63        mode,
64        as_of,
65    ) {
66        Ok(text) | Err(text) => text,
67    }
68}
69
70/// [`handle`] with a typed outcome: `Ok` is the reply, `Err` is the text of a
71/// failed call — the same text [`handle`] answers, after the same gates.
72///
73/// Typed as failures are the refusals every action shares (knowledge
74/// protection unavailable, output withheld by policy, recovered text not
75/// admitted) and every failure of `recall`, `timeline` and `search` — the
76/// actions that declare every source
77/// (`CtxKnowledgeTool::publishes_every_source`), whose error text must never
78/// be recorded as a delivery of the sources captured before the failure. The
79/// other actions still answer their own failures as reply text.
80#[allow(clippy::too_many_arguments)]
81pub fn handle_outcome(
82    project_root: &str,
83    action: &str,
84    category: Option<&str>,
85    key: Option<&str>,
86    value: Option<&str>,
87    query: Option<&str>,
88    session_id: &str,
89    pattern_type: Option<&str>,
90    examples: Option<Vec<String>>,
91    confidence: Option<f32>,
92    mode: Option<&str>,
93    as_of: Option<&str>,
94) -> Result<String, String> {
95    handle_outcome_windowed(
96        project_root,
97        action,
98        category,
99        key,
100        value,
101        query,
102        session_id,
103        pattern_type,
104        examples,
105        confidence,
106        mode,
107        as_of,
108        RecallWindow::default(),
109    )
110}
111
112/// [`handle_outcome`] with the window of a category listing (`recall` with
113/// `category`: per-call `limit`/`offset`, #2248). Other actions ignore it.
114#[allow(clippy::too_many_arguments)]
115pub fn handle_outcome_windowed(
116    project_root: &str,
117    action: &str,
118    category: Option<&str>,
119    key: Option<&str>,
120    value: Option<&str>,
121    query: Option<&str>,
122    session_id: &str,
123    pattern_type: Option<&str>,
124    examples: Option<Vec<String>>,
125    confidence: Option<f32>,
126    mode: Option<&str>,
127    as_of: Option<&str>,
128    window: RecallWindow,
129) -> Result<String, String> {
130    if let Err(error) = lean_ctx::core::knowledge::protection::current(project_root) {
131        return Err(format!("Error: {error}"));
132    }
133    lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
134        std::cell::RefCell::new(Some(std::path::PathBuf::from(project_root))),
135        || {
136    let declared = match action {
137        "recall" => Some(handle_recall(project_root, category, query, session_id, mode, as_of, window)),
138        "timeline" => Some(handle_timeline(project_root, category)),
139        "search" => Some(handle_search(query, session_id)),
140        _ => None,
141    };
142    let failed = matches!(declared, Some(Err(_)));
143    let result = match declared {
144        Some(Ok(text) | Err(text)) => text,
145        None => match action {
146        "policy" => handle_policy(value),
147        "remember" => handle_remember(project_root, category, key, value, session_id, confidence),
148        "pattern" => handle_pattern(project_root, pattern_type, value, examples, session_id),
149        "feedback" => handle_feedback(project_root, category, key, value, session_id),
150        "relate" => crate::tools::ctx_knowledge_relations::handle_relate(
151            project_root,
152            category,
153            key,
154            value,
155            query,
156            session_id,
157        ),
158        "unrelate" => crate::tools::ctx_knowledge_relations::handle_unrelate(
159            project_root,
160            category,
161            key,
162            value,
163            query,
164        ),
165        "relations" => crate::tools::ctx_knowledge_relations::handle_relations(
166            project_root,
167            category,
168            key,
169            value,
170            query,
171        ),
172        "relations_diagram" => crate::tools::ctx_knowledge_relations::handle_relations_diagram(
173            project_root,
174            category,
175            key,
176            value,
177            query,
178        ),
179        "status" => handle_status(project_root),
180        "changes" => changes::handle_changes(project_root, query, session_id),
181        "repin" => changes::handle_repin(project_root, category, key),
182        "coverage" => changes::handle_coverage(project_root),
183        "health" => handle_health(project_root),
184        "lifecycle_report" => handle_lifecycle_report(project_root),
185        "remove" => handle_remove(project_root, category, key),
186        "export" => handle_export(project_root),
187        "consolidate" => handle_consolidate(project_root),
188        "consolidate_preview" => handle_consolidate_preview(project_root),
189        "restore" => handle_restore(project_root, category, query, None),
190        "rooms" => handle_rooms(project_root),
191        "wakeup" => handle_wakeup(project_root),
192        "embeddings_status" => handle_embeddings_status(project_root),
193        "embeddings_reset" => handle_embeddings_reset(project_root),
194        "embeddings_reindex" => handle_embeddings_reindex(project_root),
195        "judge" => handle_judge(project_root, category, key, value, query),
196        // Deprecated no-op (rust/data/DEPRECATIONS.toml): accepted until removal.
197        "cognition_loop" => "ctx_knowledge action=cognition_loop is retired and has no effect: scheduled consolidation already runs the memory lifecycle (decay, merge, archival). Use action=consolidate to run it now.".to_string(),
198        "bridge_publish" => handle_bridge_publish(project_root, session_id),
199        "bridge_pull" => handle_bridge_pull(project_root, session_id),
200        "bridge_status" => handle_bridge_status(project_root),
201        _ => format!(
202            "Unknown action: {action}. Use: policy, remember, recall, pattern, feedback, judge, relate, unrelate, relations, relations_diagram, status, health, lifecycle_report, remove, export, consolidate, consolidate_preview, restore, timeline, rooms, search, wakeup, embeddings_status, embeddings_reset, embeddings_reindex, bridge_publish, bridge_pull, bridge_status"
203        ),
204        },
205    };
206    let Ok(result) = lean_ctx::core::policy::content::protect_active(&result) else {
207        return Err("Error: knowledge output withheld by current policy".to_string());
208    };
209    // A fact value that is a JSON document carries a credential member's
210    // secret nested (`{"token":["S"]}`) where the text rules cannot see it:
211    // the whole value of every such member is masked in every view.
212    let result = match lean_ctx::core::redaction::structured::mask_structured_text(&result) {
213        Ok(None) => result.to_string(),
214        Ok(Some(masked)) if !masked.still_carries_an_original() => masked.text,
215        Ok(Some(_)) => {
216            return Err("Error: knowledge output withheld: a masked value appears elsewhere".to_string());
217        }
218        Err(_) => return Err("Error: knowledge output withheld: not inspectable".to_string()),
219    };
220    // Stored knowledge is recovered text: every view of it passes the context
221    // gateway under the current policy, including facts written before the
222    // store admitted its input (G5). A failure text passes the same gates.
223    match lean_ctx::core::context_admission::recovery::admit_recovered(&result, "knowledge") {
224        Ok(text) if failed => Err(text),
225        Ok(text) if action == "wakeup" => Ok(wakeup_delta(value, text)),
226        Ok(text) => Ok(text),
227        Err(error) => Err(format!("Error: {error}")),
228    }
229        },
230    )
231}
232
233fn handle_policy(value: Option<&str>) -> String {
234    let sub = value.unwrap_or("show").trim().to_lowercase();
235    let profile = lean_ctx::core::profiles::active_profile_name();
236
237    match sub.as_str() {
238        "show" => {
239            let policy = match load_policy_or_error() {
240                Ok(p) => p,
241                Err(e) => return e,
242            };
243
244            let cfg_path = lean_ctx::core::config::Config::path().map_or_else(
245                || "~/.lean-ctx/config.toml".to_string(),
246                |p| p.display().to_string(),
247            );
248
249            format!(
250                "Knowledge policy (effective, profile={profile}):\n\
251                 - memory.knowledge facts: no limit (max_facts is ignored)\n\
252                 - memory.knowledge.contradiction_threshold={}\n\
253                 - memory.knowledge.recall_facts_limit={}\n\
254                 - memory.knowledge.rooms_limit={}\n\
255                 - memory.knowledge.timeline_limit={}\n\
256                 - memory.knowledge.relations_limit={}\n\
257                 - memory.lifecycle.decay_rate={}\n\
258                 - memory.lifecycle.stale_days={}\n\
259                 \nConfig: {cfg_path}",
260                policy.knowledge.contradiction_threshold,
261                policy.knowledge.recall_facts_limit,
262                policy.knowledge.rooms_limit,
263                policy.knowledge.timeline_limit,
264                policy.knowledge.relations_limit,
265                policy.lifecycle.decay_rate,
266                policy.lifecycle.stale_days
267            )
268        }
269        "validate" => match load_policy_or_error() {
270            Ok(_) => format!("OK: memory policy valid (profile={profile})"),
271            Err(e) => e,
272        },
273        _ => "Error: policy value must be show|validate".to_string(),
274    }
275}
276
277fn handle_feedback(
278    project_root: &str,
279    category: Option<&str>,
280    key: Option<&str>,
281    value: Option<&str>,
282    session_id: &str,
283) -> String {
284    let Some(cat) = category else {
285        return "Error: category is required for feedback".to_string();
286    };
287    let Some(k) = key else {
288        return "Error: key is required for feedback".to_string();
289    };
290    let dir = value.unwrap_or("up").trim().to_lowercase();
291    let is_up = matches!(dir.as_str(), "up" | "+1" | "+" | "true" | "1");
292    let is_down = matches!(dir.as_str(), "down" | "-1" | "-" | "false" | "0");
293    if !is_up && !is_down {
294        return "Error: feedback value must be up|down (+1|-1)".to_string();
295    }
296
297    // Read-modify-write under the cross-process lock (#326/#594) so concurrent
298    // CLI/daemon/MCP feedback never clobbers each other.
299    let outcome = ProjectKnowledge::mutate_locked(project_root, |knowledge| {
300        let Some(f) = knowledge
301            .facts
302            .iter_mut()
303            .find(|f| f.is_current() && f.category == cat && f.key == k)
304        else {
305            return Err(format!("No current fact found: [{cat}] {k}"));
306        };
307
308        if is_up {
309            f.feedback_up = f.feedback_up.saturating_add(1);
310        } else {
311            f.feedback_down = f.feedback_down.saturating_add(1);
312        }
313        f.last_feedback = Some(UtcDateTime::now());
314        Ok((
315            f.quality_score(),
316            f.feedback_up,
317            f.feedback_down,
318            f.confidence,
319        ))
320    });
321
322    let (quality, up, down, conf) = match outcome {
323        Ok((_, Ok(vals))) => vals,
324        Ok((_, Err(msg))) => return msg,
325        Err(e) => return format!("Error: feedback was not saved: {e}"),
326    };
327
328    lean_ctx::core::events::emit(lean_ctx::core::events::EventKind::KnowledgeUpdate {
329        category: cat.to_string(),
330        key: k.to_string(),
331        action: if is_up {
332            "feedback_up"
333        } else {
334            "feedback_down"
335        }
336        .to_string(),
337    });
338
339    format!(
340        "Feedback recorded ({dir}) for [{cat}] {k} (up={up}, down={down}, quality={quality:.2}, confidence={conf:.2}, session={session_id})"
341    )
342}
343
344pub(crate) fn handle_judge(
345    project_root: &str,
346    category: Option<&str>,
347    key: Option<&str>,
348    value: Option<&str>,
349    query: Option<&str>,
350) -> String {
351    let source = match (category, key) {
352        (Some(cat), Some(k)) => format!("{cat}/{k}"),
353        _ => {
354            if let Some(k) = key.or(category) {
355                if k.contains('/') {
356                    k.to_string()
357                } else {
358                    return "Error: judge requires key as 'category/key' (source fact)".to_string();
359                }
360            } else {
361                return "Error: judge requires category+key (source fact) and value (target 'category/key')"
362                    .to_string();
363            }
364        }
365    };
366
367    let Some(target) = value else {
368        return "Error: judge requires value as target 'category/key'".to_string();
369    };
370    let target = target.trim().to_string();
371    if !target.contains('/') {
372        return "Error: target must be 'category/key' format".to_string();
373    }
374
375    let verdict = query.unwrap_or("compatible").trim().to_lowercase();
376    if !matches!(
377        verdict.as_str(),
378        "supersedes" | "compatible" | "unrelated" | "contradicts"
379    ) {
380        return format!(
381            "Error: verdict must be supersedes|compatible|unrelated|contradicts, got '{verdict}'"
382        );
383    }
384
385    // Read-modify-write under the cross-process lock (#326/#594).
386    let result = ProjectKnowledge::mutate_locked(project_root, |knowledge| {
387        let src = current_fact_index(knowledge, &source)?;
388        let tgt = current_fact_index(knowledge, &target)?;
389        if src == tgt {
390            return Err("Error: a fact is not judged against itself".to_string());
391        }
392        let now = UtcDateTime::now();
393
394        if verdict == "supersedes" {
395            let tf = &mut knowledge.facts[tgt];
396            tf.valid_until = Some(now);
397            tf.valid_from = tf.valid_from.or(Some(tf.created_at));
398            // The survivor of a judged contradiction is no longer contradicted.
399            let sf = &mut knowledge.facts[src];
400            if sf.review.as_ref().is_some_and(|r| {
401                r.reason == lean_ctx::core::knowledge::FactReviewReason::Contradiction
402            }) {
403                sf.clear_review();
404            }
405        }
406        // J2: both stay current and both are marked until one supersedes the
407        // other. A Cloud fact's state reaches Cloud with the next sync
408        // (C0 1.9 section 3), which opens a task when nobody resolves it.
409        if verdict == "contradicts" {
410            use lean_ctx::core::knowledge::{FactReviewReason, FactReviewState};
411            for i in [src, tgt] {
412                knowledge.facts[i].mark_review(
413                    FactReviewState::Contradicted,
414                    FactReviewReason::Contradiction,
415                    now,
416                );
417            }
418        }
419
420        knowledge
421            .judged_pairs
422            .push(lean_ctx::core::knowledge::JudgedPair {
423                key_a: source.clone(),
424                key_b: target.clone(),
425                verdict: verdict.clone(),
426                judged_at: now,
427            });
428        Ok(())
429    });
430
431    match result {
432        Ok((_, Ok(()))) => {}
433        Ok((_, Err(msg))) => return msg,
434        Err(e) => return format!("Error: judge save failed: {e}"),
435    }
436
437    let action_desc = match verdict.as_str() {
438        "supersedes" => format!("{source} supersedes {target} (target archived)"),
439        "compatible" => format!("{source} ↔ {target} (compatible, suppressed from future similar)"),
440        "unrelated" => format!("{source} ≠ {target} (unrelated, suppressed from future similar)"),
441        "contradicts" => format!(
442            "{source} ⟂ {target} (contradicts: both marked contradicted until one supersedes the other)"
443        ),
444        _ => unreachable!(),
445    };
446
447    format!("Judged: {action_desc}")
448}
449
450/// The current fact named `spec` (`category/key`; categories and keys may
451/// contain `/`, so the whole name is matched).
452fn current_fact_index(
453    knowledge: &lean_ctx::core::knowledge::ProjectKnowledge,
454    spec: &str,
455) -> Result<usize, String> {
456    let mut found = knowledge.facts.iter().enumerate().filter(|(_, f)| {
457        f.is_current()
458            && spec.len() == f.category.len() + 1 + f.key.len()
459            && spec.starts_with(f.category.as_str())
460            && spec[f.category.len()..].starts_with('/')
461            && spec.ends_with(f.key.as_str())
462    });
463    match (found.next(), found.next()) {
464        (Some((i, _)), None) => Ok(i),
465        (Some(_), Some(_)) => Err(format!("Error: '{spec}' names more than one current fact")),
466        (None, _) => Err(format!("Error: no current fact found for '{spec}'")),
467    }
468}
469
470fn handle_pattern(
471    project_root: &str,
472    pattern_type: Option<&str>,
473    value: Option<&str>,
474    examples: Option<Vec<String>>,
475    session_id: &str,
476) -> String {
477    let Some(pt) = pattern_type else {
478        return "Error: pattern_type is required".to_string();
479    };
480    let Some(desc) = value else {
481        return "Error: value (description) is required for pattern".to_string();
482    };
483    let exs = examples.unwrap_or_default();
484    let policy = match lean_ctx::core::config::Config::load().memory_policy_effective() {
485        Ok(p) => p,
486        Err(e) => {
487            let path = lean_ctx::core::config::Config::path().map_or_else(
488                || "~/.lean-ctx/config.toml".to_string(),
489                |p| p.display().to_string(),
490            );
491            return format!("Error: invalid memory policy: {e}\nFix: edit {path}");
492        }
493    };
494    // Read-modify-write under the cross-process lock (#326/#594).
495    match ProjectKnowledge::mutate_locked(project_root, |knowledge| {
496        knowledge.add_pattern(pt, desc, exs, session_id, &policy);
497    }) {
498        Ok(_) => format!("Pattern [{pt}] added: {desc}"),
499        Err(e) => format!("Pattern add failed: {e}"),
500    }
501}
502
503fn handle_status(project_root: &str) -> String {
504    let Some(knowledge) = ProjectKnowledge::load(project_root) else {
505        return "No knowledge stored for this project yet. Use ctx_knowledge(action=\"remember\") to start.".to_string();
506    };
507
508    let current_facts = knowledge.facts.iter().filter(|f| f.is_current()).count();
509    let archived_facts = knowledge.facts.len() - current_facts;
510
511    let mut out = format!(
512        "Project Knowledge: {} active facts ({} archived), {} patterns, {} history entries\n",
513        current_facts,
514        archived_facts,
515        knowledge.patterns.len(),
516        knowledge.history.len()
517    );
518    out.push_str(&format!(
519        "Last updated: {}\n",
520        knowledge.updated_at.format("%Y-%m-%d %H:%M UTC")
521    ));
522
523    let rooms = knowledge.list_rooms();
524    if !rooms.is_empty() {
525        out.push_str("Rooms: ");
526        let room_strs: Vec<String> = rooms.iter().map(|(c, n)| format!("{c}({n})")).collect();
527        out.push_str(&room_strs.join(", "));
528        out.push('\n');
529    }
530
531    out.push_str(&knowledge.format_summary());
532    out
533}
534
535/// Per-layer lifecycle report (GL#445): item counts, effective policies, and
536/// the next enforcement action for every memory layer. Read-only.
537fn handle_lifecycle_report(project_root: &str) -> String {
538    let policy = match load_policy_or_error() {
539        Ok(p) => p,
540        Err(e) => return e,
541    };
542
543    let mut out = String::from("=== Memory Lifecycle Report ===\n");
544
545    // Knowledge layer (long-term facts, archive-only eviction).
546    match ProjectKnowledge::load(project_root) {
547        Some(k) => {
548            let active = k.facts.iter().filter(|f| f.is_current()).count();
549            let archived = k.facts.len() - active;
550            out.push_str(&format!(
551                "knowledge   {active} active / {archived} archived (no fact limit)\n\
552                 \x20           decay {}/day, stale >{}d, consolidate-sim {:.2}\n\
553                 \x20           GC: by quality only (decay, near-duplicate merge, low-confidence/stale); eviction archives, never deletes\n",
554                policy.lifecycle.decay_rate,
555                policy.lifecycle.stale_days,
556                policy.lifecycle.similarity_threshold,
557            ));
558        }
559        None => out.push_str("knowledge   (no store yet)\n"),
560    }
561
562    // Archive files (restorable via recall rehydration).
563    let archives = lean_ctx::core::memory_lifecycle::list_archives(project_root);
564    out.push_str(&format!(
565        "archives    {} file(s); auto-rehydrated when recall misses\n",
566        archives.len()
567    ));
568
569    // Embeddings layer (semantic index over knowledge facts).
570    #[cfg(feature = "embeddings")]
571    {
572        let hash = lean_ctx::core::project_hash::hash_project_root(project_root);
573        let n = lean_ctx::core::knowledge_embedding::KnowledgeEmbeddingIndex::load(&hash)
574            .map_or(0, |idx| idx.entries.len());
575        out.push_str(&format!(
576            "embeddings  {n} vector(s); compacted against knowledge on remember\n"
577        ));
578    }
579    #[cfg(not(feature = "embeddings"))]
580    out.push_str("embeddings  (feature disabled in this build)\n");
581
582    out.push_str(
583        "\nLayer boundaries: session = working memory (now) | knowledge = long-term (ETL via consolidate) | providers = external (read-through)\n",
584    );
585    out
586}
587
588fn handle_health(project_root: &str) -> String {
589    let Some(knowledge) = ProjectKnowledge::load(project_root) else {
590        return "No knowledge stored. Nothing to report.".to_string();
591    };
592
593    let total = knowledge.facts.len();
594    let current: Vec<_> = knowledge.facts.iter().filter(|f| f.is_current()).collect();
595    let archived = total - current.len();
596
597    let mut low_quality = 0u32;
598    let mut high_quality = 0u32;
599    let mut stale_candidates = 0u32;
600    let mut total_quality: f32 = 0.0;
601    let mut never_retrieved = 0u32;
602    let mut room_counts: std::collections::HashMap<String, (u32, f32)> =
603        std::collections::HashMap::new();
604
605    let now = lean_ctx_time::UtcDateTime::now();
606    for f in &current {
607        let q = f.quality_score();
608        total_quality += q;
609        if q < 0.4 {
610            low_quality += 1;
611        } else if q >= 0.8 {
612            high_quality += 1;
613        }
614        if f.retrieval_count == 0 {
615            never_retrieved += 1;
616        }
617        let age_days = (now - f.created_at).num_days();
618        if age_days > 30 && f.retrieval_count == 0 {
619            stale_candidates += 1;
620        }
621
622        let entry = room_counts.entry(f.category.clone()).or_insert((0, 0.0));
623        entry.0 += 1;
624        entry.1 += q;
625    }
626
627    let avg_quality = if current.is_empty() {
628        0.0
629    } else {
630        total_quality / current.len() as f32
631    };
632
633    let mut out = String::from("=== Knowledge Health Report ===\n");
634    out.push_str(&format!(
635        "Total: {} facts ({} active, {} archived)\n",
636        total,
637        current.len(),
638        archived
639    ));
640    out.push_str(&format!("Avg Quality: {avg_quality:.2}\n"));
641    out.push_str(&format!(
642        "Distribution: {high_quality} high (>=0.8) | {low_quality} low (<0.4)\n"
643    ));
644    out.push_str(&format!(
645        "Stale (>30d, never retrieved): {stale_candidates}\n"
646    ));
647    out.push_str(&format!("Never retrieved: {never_retrieved}\n"));
648
649    if !room_counts.is_empty() {
650        out.push_str("\nRoom Balance:\n");
651        let mut rooms: Vec<_> = room_counts.into_iter().collect();
652        rooms.sort_by_key(|x| std::cmp::Reverse(x.1.0));
653        for (cat, (count, total_q)) in &rooms {
654            let avg = if *count > 0 {
655                total_q / *count as f32
656            } else {
657                0.0
658            };
659            out.push_str(&format!("  {cat}: {count} facts, avg quality {avg:.2}\n"));
660        }
661    }
662
663    let policy = lean_ctx::core::config::Config::load()
664        .memory_policy_effective()
665        .unwrap_or_default();
666    out.push_str(&format!(
667        "\nPolicy: no fact limit, max {} patterns\n",
668        policy.knowledge.max_patterns
669    ));
670
671    out
672}
673
674fn handle_remove(project_root: &str, category: Option<&str>, key: Option<&str>) -> String {
675    let Some(cat) = category else {
676        return "Error: category is required for remove".to_string();
677    };
678    let Some(k) = key else {
679        return "Error: key is required for remove".to_string();
680    };
681    let policy = match lean_ctx::core::config::Config::load().memory_policy_effective() {
682        Ok(p) => p,
683        Err(e) => {
684            let path = lean_ctx::core::config::Config::path().map_or_else(
685                || "~/.lean-ctx/config.toml".to_string(),
686                |p| p.display().to_string(),
687            );
688            return format!("Error: invalid memory policy: {e}\nFix: edit {path}");
689        }
690    };
691    // Read-modify-write under the cross-process lock (#326/#594). The embedding
692    // index is a separate store, so it is synced afterwards from the committed
693    // knowledge — mirroring handle_remember.
694    let (knowledge, removed) = match ProjectKnowledge::mutate_locked(project_root, |knowledge| {
695        knowledge.remove_fact(cat, k)
696    }) {
697        Ok(pair) => pair,
698        Err(e) => return format!("Error: removal was not saved: {e}"),
699    };
700
701    if !removed {
702        return format!("No fact found: [{cat}] {k}");
703    }
704
705    #[cfg(feature = "embeddings")]
706    {
707        // Serialize the embedding side-car under the same per-project lock as
708        // the fact removal and compact against fresh on-disk knowledge, so a
709        // concurrent `remember` cannot clobber it (issue #412).
710        ProjectKnowledge::with_project_lock(project_root, || {
711            if let Some(mut idx) =
712                lean_ctx::core::knowledge_embedding::KnowledgeEmbeddingIndex::load(
713                    &knowledge.project_hash,
714                )
715            {
716                idx.remove(cat, k);
717                let fresh = ProjectKnowledge::load(project_root);
718                let kref = fresh.as_ref().unwrap_or(&knowledge);
719                lean_ctx::core::knowledge_embedding::compact_against_knowledge(
720                    &mut idx, kref, &policy,
721                );
722                let _ = idx.save();
723            }
724        });
725    }
726    #[cfg(not(feature = "embeddings"))]
727    let _ = (&knowledge, &policy);
728
729    format!("Removed [{cat}] {k}")
730}
731
732fn handle_export(project_root: &str) -> String {
733    let result = lean_ctx::core::policy::runtime::with_explicit_project_source_view(
734        std::path::Path::new(project_root),
735        |authority| -> Result<String, String> {
736            let admission =
737                lean_ctx::core::knowledge::protection::KnowledgeAdmission::capture(project_root)?;
738            let Some(knowledge) = ProjectKnowledge::load_for_admission(project_root, &admission)?
739            else {
740                admission.authorize_publication(authority)?;
741                return Ok("No knowledge to export.".to_string());
742            };
743            if knowledge.facts.is_empty()
744                && knowledge.patterns.is_empty()
745                && knowledge.history.is_empty()
746            {
747                admission.authorize_publication(authority)?;
748                return Ok("No knowledge to export.".to_string());
749            }
750            let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()?;
751            let export_dir = data_dir.join("exports").join("knowledge");
752            let ts = UtcDateTime::now().format("%Y%m%d-%H%M%S");
753            let filename = format!(
754                "knowledge-{}-{ts}.json",
755                short_hash(&knowledge.project_hash)
756            );
757            let path = export_dir.join(filename);
758            let mut json = serde_json::to_string_pretty(&knowledge)
759                .map_err(|_| "Export serialization failed")?;
760            // A fact value that is a JSON document: the whole value of every
761            // credential member in it is masked, as in every other view.
762            match lean_ctx::core::redaction::structured::mask_structured_text(&json) {
763                Ok(None) => {}
764                Ok(Some(masked)) if !masked.still_carries_an_original() => json = masked.text,
765                Ok(Some(_)) | Err(_) => return Err("export withheld: secret not maskable".into()),
766            }
767            json.push('\n');
768            admission.authorize_publication(authority)?;
769            lean_ctx::config_io::write_atomic_with_backup(&path, &json)?;
770            Ok(format!(
771                "Export saved: {} (active facts: {}, patterns: {}, history: {})",
772                path.display(),
773                knowledge.facts.iter().filter(|f| f.is_current()).count(),
774                knowledge.patterns.len(),
775                knowledge.history.len()
776            ))
777        },
778    );
779    match result {
780        Ok(Ok(message)) => message,
781        Ok(Err(error)) | Err(error) => format!("Export failed: {error}"),
782    }
783}
784
785fn admitted_snapshot(
786    project_root: &str,
787    admission: &lean_ctx::core::knowledge::protection::KnowledgeAdmission,
788) -> Result<Option<lean_ctx::core::knowledge::KnowledgeSnapshot>, String> {
789    let Some(knowledge) = ProjectKnowledge::load_for_admission(project_root, admission)? else {
790        return Ok(None);
791    };
792    let visible_nodes: std::collections::HashSet<(String, String)> = knowledge
793        .facts
794        .iter()
795        .map(|fact| (fact.category.clone(), fact.key.clone()))
796        .collect();
797    let relations =
798        lean_ctx::core::knowledge_relations::KnowledgeRelationGraph::load(&knowledge.project_hash)
799            .map(|graph| {
800                graph
801                    .edges
802                    .into_iter()
803                    .filter(|edge| {
804                        visible_nodes.contains(&(edge.from.category.clone(), edge.from.key.clone()))
805                            && visible_nodes
806                                .contains(&(edge.to.category.clone(), edge.to.key.clone()))
807                            && serde_json::to_value(edge)
808                                .is_ok_and(|value| admission.admits_archive_value(&value))
809                    })
810                    .collect()
811            })
812            .unwrap_or_default();
813    admission.authorize_gateway()?;
814    Ok(Some(
815        lean_ctx::core::knowledge::KnowledgeSnapshot::from_project(&knowledge, relations),
816    ))
817}
818
819/// Exports the project's current knowledge as an Open Knowledge Format (OKF)
820/// bundle — a directory of Markdown files, portable and vendor-neutral. Renders
821/// from the shared [`lean_ctx::core::knowledge::KnowledgeSnapshot`], so it never
822/// disagrees with a ctxpkg export on what the knowledge is. `out` is the target
823/// directory (defaults to the data dir's `exports/okf/<hash>`).
824pub fn handle_export_okf(project_root: &str, out: Option<&str>) -> String {
825    let result = lean_ctx::core::policy::runtime::with_explicit_project_source_view(
826        std::path::Path::new(project_root),
827        |authority| -> Result<String, String> {
828            let admission =
829                lean_ctx::core::knowledge::protection::KnowledgeAdmission::capture(project_root)?;
830            let Some(snapshot) = admitted_snapshot(project_root, &admission)? else {
831                admission.authorize_publication(authority)?;
832                return Ok("No knowledge to export.".to_string());
833            };
834            if snapshot.is_empty() {
835                admission.authorize_publication(authority)?;
836                return Ok("No knowledge to export.".to_string());
837            }
838            let dir = match out {
839                Some(p) => std::path::PathBuf::from(p),
840                None => lean_ctx::core::data_dir::lean_ctx_data_dir()?
841                    .join("exports")
842                    .join("okf")
843                    .join(short_hash(&snapshot.project_hash)),
844            };
845            let bundle = lean_ctx::core::knowledge::okf::to_okf_bundle(&snapshot);
846            admission.authorize_publication(authority)?;
847            lean_ctx::core::knowledge::okf::write_okf_bundle(&dir, &bundle)?;
848            Ok(format!(
849                "OKF bundle exported: {} ({} concepts, {} patterns, {} relations)",
850                dir.display(),
851                snapshot.current_facts().len(),
852                snapshot.patterns.len(),
853                snapshot.relations.len()
854            ))
855        },
856    );
857    match result {
858        Ok(Ok(message)) => message,
859        Ok(Err(error)) | Err(error) => format!("Export failed: {error}"),
860    }
861}
862
863/// Imports knowledge from `path`. A directory is treated as an OKF bundle; a
864/// file falls back to the native JSON / simple-array / JSONL import.
865pub fn handle_import(
866    project_root: &str,
867    path: &str,
868    merge: lean_ctx::core::knowledge::ImportMerge,
869    session_id: &str,
870) -> String {
871    if std::path::Path::new(path).is_dir() {
872        return handle_import_okf(project_root, std::path::Path::new(path), merge, session_id);
873    }
874
875    let data = match std::fs::read_to_string(path) {
876        Ok(d) => d,
877        Err(e) => return format!("Failed to read {path}: {e}"),
878    };
879    let facts = match lean_ctx::core::knowledge::parse_import_data(&data) {
880        Ok(f) => f,
881        Err(e) => return format!("Parse error: {e}"),
882    };
883    match ProjectKnowledge::mutate_locked(project_root, |k| {
884        k.import_facts(facts, merge, session_id)
885    }) {
886        Ok((_, r)) => format!(
887            "Import complete: {} added, {} skipped, {} replaced",
888            r.added, r.skipped, r.replaced
889        ),
890        Err(e) => format!("Import failed: {e}"),
891    }
892}
893
894/// OKF directory import: facts via `import_facts`, patterns via `add_pattern`,
895/// then relations via the relation graph — guarded so an edge is only created
896/// when both endpoints are current facts (facts first, then edges).
897fn handle_import_okf(
898    project_root: &str,
899    dir: &std::path::Path,
900    merge: lean_ctx::core::knowledge::ImportMerge,
901    session_id: &str,
902) -> String {
903    let imp = match lean_ctx::core::knowledge::okf::from_okf_dir(dir) {
904        Ok(i) => i,
905        Err(e) => return format!("OKF import failed: {e}"),
906    };
907    let policy = match load_policy_or_error() {
908        Ok(p) => p,
909        Err(e) => return e,
910    };
911
912    let pattern_count = imp.patterns.len();
913    let (knowledge, result) = match ProjectKnowledge::mutate_locked(project_root, |k| {
914        let r = k.import_facts(imp.facts, merge, session_id);
915        for p in &imp.patterns {
916            k.add_pattern(
917                &p.pattern_type,
918                &p.description,
919                p.examples.clone(),
920                session_id,
921                &policy,
922            );
923        }
924        r
925    }) {
926        Ok(v) => v,
927        Err(e) => return format!("OKF import failed: {e}"),
928    };
929
930    // Guarded edges: only between facts that are current after the import.
931    let current: std::collections::HashSet<(String, String)> = knowledge
932        .facts
933        .iter()
934        .filter(|f| f.is_current())
935        .map(|f| (f.category.clone(), f.key.clone()))
936        .collect();
937    let mut relations_added = 0usize;
938    if !imp.edges.is_empty() {
939        let saved = lean_ctx::core::knowledge_relations::KnowledgeRelationGraph::mutate_locked(
940            project_root,
941            &knowledge.project_hash,
942            |graph| {
943                let mut added = 0usize;
944                for e in imp.edges {
945                    let endpoints_current = current
946                        .contains(&(e.from.category.clone(), e.from.key.clone()))
947                        && current.contains(&(e.to.category.clone(), e.to.key.clone()));
948                    if endpoints_current && graph.upsert_edge(e.from, e.to, e.kind, session_id) {
949                        added += 1;
950                    }
951                }
952                Some(added)
953            },
954        );
955        match saved {
956            Ok(added) => relations_added = added.unwrap_or_default(),
957            Err(err) => tracing::warn!("OKF import: relations save failed: {err}"),
958        }
959    }
960
961    let mut out = format!(
962        "OKF import: {} added, {} skipped, {} replaced, {pattern_count} patterns, {relations_added} relations",
963        result.added, result.skipped, result.replaced
964    );
965    let warnings = lean_ctx::core::knowledge::okf::lint_okf_bundle(dir);
966    if !warnings.is_empty() {
967        out.push_str(&format!("\nLint warnings ({}):", warnings.len()));
968        for w in warnings.iter().take(10) {
969            out.push_str(&format!("\n  - {w}"));
970        }
971    }
972    out
973}
974
975fn handle_consolidate(project_root: &str) -> String {
976    match consolidate_project_knowledge(project_root) {
977        Ok(report) => format_consolidation_report(&report),
978        Err(e) => e,
979    }
980}
981
982/// Dry-run consolidate: preview imports + reclaim with zero writes (#995).
983fn handle_consolidate_preview(project_root: &str) -> String {
984    match consolidate_project_knowledge_with(
985        project_root,
986        &ConsolidateOptions::manual().into_dry_run(),
987    ) {
988        Ok(report) => format_consolidation_report(&report),
989        Err(e) => e,
990    }
991}
992
993/// Explicit cross-store restore from archive (#995 Phase 6). `store` selects a
994/// single store (all when `None`); `query` filters by substring; `limit` caps
995/// the total restored (default [`DEFAULT_RESTORE_LIMIT`]).
996fn handle_restore(
997    project_root: &str,
998    store: Option<&str>,
999    query: Option<&str>,
1000    limit: Option<usize>,
1001) -> String {
1002    let store = match store {
1003        Some(s) if lean_ctx::core::memory_archive::MemoryStore::is_retired(s) => {
1004            return lean_ctx::core::memory_archive::RETIRED_PROCEDURES_STORE_NOTICE.to_string();
1005        }
1006        Some(s) => match lean_ctx::core::memory_archive::MemoryStore::parse(s) {
1007            Some(ms) => Some(ms),
1008            None => {
1009                return format!("Unknown store: {s}. Use: facts, history, patterns");
1010            }
1011        },
1012        None => None,
1013    };
1014    let opts = RestoreOptions::new(
1015        store,
1016        query.map(str::to_string),
1017        limit.unwrap_or(DEFAULT_RESTORE_LIMIT),
1018    );
1019    match run_restore(project_root, &opts) {
1020        Ok(report) => format_restore_report(&report),
1021        Err(e) => e,
1022    }
1023}
1024
1025fn handle_timeline(project_root: &str, category: Option<&str>) -> Result<String, String> {
1026    let Some(knowledge) = ProjectKnowledge::load(project_root) else {
1027        return Ok("No knowledge stored yet.".to_string());
1028    };
1029
1030    let policy = load_policy_or_error()?;
1031
1032    let Some(cat) = category else {
1033        return Err("Error: category is required for timeline".to_string());
1034    };
1035
1036    let facts = knowledge.timeline(cat);
1037    if facts.is_empty() {
1038        return Ok(format!("No history for category '{cat}'."));
1039    }
1040
1041    let mut ordered: Vec<&lean_ctx::core::knowledge::KnowledgeFact> = facts;
1042    ordered.sort_by(|a, b| {
1043        let a_start = a.valid_from.unwrap_or(a.created_at);
1044        let b_start = b.valid_from.unwrap_or(b.created_at);
1045        a_start
1046            .cmp(&b_start)
1047            .then_with(|| a.last_confirmed.cmp(&b.last_confirmed))
1048            .then_with(|| a.key.cmp(&b.key))
1049            .then_with(|| a.value.cmp(&b.value))
1050    });
1051
1052    let total = ordered.len();
1053    let limit = policy.knowledge.timeline_limit;
1054    if ordered.len() > limit {
1055        ordered = ordered[ordered.len() - limit..].to_vec();
1056    }
1057    // Only what may be delivered now (see `fact_served`).
1058    ordered.retain(|f| fact_served(project_root, &f.category, &f.key, &f.value));
1059
1060    let mut out = format!(
1061        "Timeline [{cat}] (showing {}/{} entries):\n",
1062        ordered.len(),
1063        total
1064    );
1065    for f in &ordered {
1066        let status = if f.is_current() {
1067            "CURRENT"
1068        } else {
1069            "archived"
1070        };
1071        let valid_range = match (f.valid_from, f.valid_until) {
1072            (Some(from), Some(until)) => format!(
1073                "{} → {}",
1074                from.format("%Y-%m-%d %H:%M"),
1075                until.format("%Y-%m-%d %H:%M")
1076            ),
1077            (Some(from), None) => format!("{} → now", from.format("%Y-%m-%d %H:%M")),
1078            _ => "unknown".to_string(),
1079        };
1080        out.push_str(&format!(
1081            "  {} = {} [{status}] ({valid_range}) conf={:.0}% x{}\n",
1082            f.key,
1083            f.as_delivered(f.value.clone()),
1084            f.confidence * 100.0,
1085            f.confirmation_count
1086        ));
1087    }
1088    Ok(out)
1089}
1090
1091fn handle_rooms(project_root: &str) -> String {
1092    let Some(knowledge) = ProjectKnowledge::load(project_root) else {
1093        return "No knowledge stored yet.".to_string();
1094    };
1095
1096    let policy = match load_policy_or_error() {
1097        Ok(p) => p,
1098        Err(e) => return e,
1099    };
1100
1101    let rooms = knowledge.list_rooms();
1102    if rooms.is_empty() {
1103        return "No knowledge rooms yet. Use ctx_knowledge(action=\"remember\", category=\"...\") to create rooms.".to_string();
1104    }
1105
1106    let mut rooms = rooms;
1107    rooms.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1108    let total = rooms.len();
1109    rooms.truncate(policy.knowledge.rooms_limit);
1110
1111    let mut out = format!(
1112        "Knowledge Rooms (showing {}/{} rooms, project: {}):\n",
1113        rooms.len(),
1114        total,
1115        short_hash(&knowledge.project_hash)
1116    );
1117    for (cat, count) in &rooms {
1118        out.push_str(&format!("  [{cat}] {count} fact(s)\n"));
1119    }
1120    out
1121}
1122
1123fn handle_bridge_publish(project_root: &str, session_id: &str) -> String {
1124    let knowledge = ProjectKnowledge::load_or_create(project_root);
1125    let published = lean_ctx::core::knowledge_bridge::KnowledgeBridge::mutate_locked(
1126        &knowledge.project_hash,
1127        |bridge| {
1128            (
1129                bridge.publish(session_id, &knowledge.facts),
1130                bridge.shared_facts.len(),
1131            )
1132        },
1133    );
1134    match published {
1135        Ok((count, total)) => {
1136            format!("Published {count} fact(s) to bridge (total: {total}, agent: {session_id})")
1137        }
1138        Err(e) => format!("Error: context publication was not saved: {e}"),
1139    }
1140}
1141
1142fn handle_bridge_pull(project_root: &str, session_id: &str) -> String {
1143    let project_hash = lean_ctx::core::project_hash::hash_project_root(project_root);
1144    let bridge = lean_ctx::core::knowledge_bridge::KnowledgeBridge::load_or_create(&project_hash);
1145    let entries = bridge.pull(session_id);
1146    if entries.is_empty() {
1147        return "No facts available from other agents.".to_string();
1148    }
1149
1150    let policy = match load_policy_or_error() {
1151        Ok(p) => p,
1152        Err(e) => return e,
1153    };
1154
1155    let missing = |target: &ProjectKnowledge,
1156                   entry: &lean_ctx::core::knowledge_bridge::BridgeEntry| {
1157        let fact = lean_ctx::core::knowledge_bridge::KnowledgeBridge::entry_to_fact(entry);
1158        let present = target
1159            .facts
1160            .iter()
1161            .any(|f| f.is_current() && f.category == fact.category && f.key == fact.key);
1162        (!present).then_some(fact)
1163    };
1164    // Nothing to import: the store is neither locked nor rewritten.
1165    let current = ProjectKnowledge::load_or_create(project_root);
1166    if entries
1167        .iter()
1168        .all(|entry| missing(&current, entry).is_none())
1169    {
1170        return format!(
1171            "Bridge has {} fact(s) from other agents, but all already exist locally.",
1172            entries.len()
1173        );
1174    }
1175
1176    // The existence check and the import run again on the store as it is
1177    // inside the project lock, so a parallel writer's facts are never
1178    // overwritten.
1179    let imported = ProjectKnowledge::mutate_locked(project_root, |target| {
1180        let mut imported = 0u32;
1181        for entry in &entries {
1182            if let Some(fact) = missing(target, entry) {
1183                target.remember(
1184                    &fact.category,
1185                    &fact.key,
1186                    &fact.value,
1187                    session_id,
1188                    fact.confidence,
1189                    &policy,
1190                );
1191                imported += 1;
1192            }
1193        }
1194        imported
1195    });
1196
1197    match imported {
1198        Ok((_, 0)) => format!(
1199            "Bridge has {} fact(s) from other agents, but all already exist locally.",
1200            entries.len()
1201        ),
1202        Ok((_, imported)) => format!(
1203            "Pulled {imported}/{} fact(s) from bridge into local knowledge.",
1204            entries.len()
1205        ),
1206        Err(e) => format!("Error: context import was not saved: {e}"),
1207    }
1208}
1209
1210fn handle_bridge_status(project_root: &str) -> String {
1211    let knowledge = ProjectKnowledge::load_or_create(project_root);
1212    let bridge =
1213        lean_ctx::core::knowledge_bridge::KnowledgeBridge::load_or_create(&knowledge.project_hash);
1214    bridge.summary()
1215}
1216
1217fn handle_wakeup(project_root: &str) -> String {
1218    let Some(knowledge) = ProjectKnowledge::load(project_root) else {
1219        return "No knowledge for wake-up briefing.".to_string();
1220    };
1221    let aaak = knowledge.format_aaak();
1222    if aaak.is_empty() {
1223        return "No knowledge yet. Start using ctx_knowledge(action=\"remember\") to build project memory.".to_string();
1224    }
1225    format!("{WAKEUP_HEAD}{aaak}")
1226}
1227
1228const WAKEUP_HEAD: &str = "WAKE-UP BRIEFING:\n";
1229
1230/// The delta form of a wake-up briefing, in the one channel that has a
1231/// history: a tool result stays in the caller's context.
1232///
1233/// The Engine cannot see a context. What it can check is the existing
1234/// possession proof of a request — the presenter capability its host showed
1235/// (`core::archive::presented`) — and what left the release point of the
1236/// tool pipeline. The short answer is given only when all three hold:
1237///
1238/// 1. the request shows an issued presenter capability that may still
1239///    present (`shown_presenter_reference`); the capability of the process,
1240///    which every connection without one shares, never counts;
1241/// 2. a briefing with exactly this admitted text was RELEASED to a request of
1242///    that same presenter ([`note_wakeup_release`], called where the result
1243///    blocks are the bytes the client receives — not when the text is built);
1244/// 3. the caller names the hash of that text in `value`.
1245///
1246/// Anything else is answered in full: no capability, another presenter,
1247/// nothing on record (another process, a result that was withheld, replaced,
1248/// shortened or compressed after it was built), a record that cannot be read in time, a
1249/// changed memory or policy (another admitted text), no or another hash.
1250/// `admitted` is the briefing after `protect_active` and `admit_recovered`.
1251fn wakeup_delta(held: Option<&str>, admitted: String) -> String {
1252    let holder = lean_ctx::core::archive::presented::shown_presenter_reference();
1253    wakeup_delta_for(holder.as_deref(), held, admitted)
1254}
1255
1256const WAKEUP_HASH_LINE: &str = "\n[memory hash ";
1257
1258fn wakeup_hash(briefing: &str) -> String {
1259    blake3::hash(briefing.as_bytes()).to_hex()[..16].to_string()
1260}
1261
1262fn wakeup_delta_for(holder: Option<&str>, held: Option<&str>, admitted: String) -> String {
1263    let Some(holder) = holder else {
1264        // No possession proof exists for this request: the briefing as before.
1265        return admitted;
1266    };
1267    if !admitted.starts_with(WAKEUP_HEAD)
1268        || admitted.contains(lean_ctx::core::sanitize::FENCE_REFUSAL)
1269    {
1270        return admitted;
1271    }
1272    let hash = wakeup_hash(&admitted);
1273    if held.map(str::trim) == Some(hash.as_str()) && wakeup_released(holder, &hash) {
1274        return format!(
1275            "{WAKEUP_HEAD}[project memory unchanged since the briefing with hash {hash}]"
1276        );
1277    }
1278    wakeup_full(&admitted, &hash)
1279}
1280
1281/// The full answer: the admitted briefing and, as its last line, its hash.
1282fn wakeup_full(admitted: &str, hash: &str) -> String {
1283    format!(
1284        "{admitted}{WAKEUP_HASH_LINE}{hash} — while this briefing is still in your context, \
1285         ctx_knowledge(action=\"wakeup\", value=\"{hash}\") answers \"unchanged\" instead of repeating it]"
1286    )
1287}
1288
1289type WakeupReleases = std::sync::Arc<tokio::sync::RwLock<Vec<(String, String)>>>;
1290
1291/// Briefings released by this process: (presenter reference, hash). Bounded,
1292/// in memory only: a new process has released nothing.
1293fn wakeup_releases() -> &'static WakeupReleases {
1294    static RELEASED: std::sync::OnceLock<WakeupReleases> = std::sync::OnceLock::new();
1295    RELEASED.get_or_init(WakeupReleases::default)
1296}
1297
1298/// Whether a briefing with this hash was released to this presenter. A record
1299/// that cannot be read within the lock bound counts as none.
1300fn wakeup_released(holder: &str, hash: &str) -> bool {
1301    crate::server::bounded_lock::read(wakeup_releases(), "ctx_knowledge wakeup release read")
1302        .is_some_and(|released| {
1303            released
1304                .iter()
1305                .any(|(presenter, released_hash)| presenter == holder && released_hash == hash)
1306        })
1307}
1308
1309/// The release point of the tool pipeline reports the text blocks a client
1310/// receives for a call that did not fail. A block counts as a released
1311/// briefing only when it holds, byte for byte and in one piece, the full
1312/// answer this module builds for the briefing it contains — from the head to
1313/// the end of the closing hash line. Text the pipeline put before or after it
1314/// (a notice, a hint, a checkpoint) takes nothing from the briefing and does
1315/// not matter; a block in which the answer was shortened anywhere (the
1316/// closing line included), compressed, redacted or replaced is no such block.
1317/// A request without an issued presenter capability records nothing.
1318pub(crate) fn note_wakeup_release(delivered_blocks: &[&str]) {
1319    let Some(holder) = lean_ctx::core::archive::presented::shown_presenter_reference() else {
1320        return;
1321    };
1322    note_wakeup_release_for(&holder, delivered_blocks);
1323}
1324
1325fn note_wakeup_release_for(holder: &str, delivered_blocks: &[&str]) {
1326    const REMEMBERED: usize = 64;
1327    for block in delivered_blocks {
1328        // Head and marker only locate the answer; what counts is that the
1329        // block holds it whole, from the head to the end of its closing line.
1330        let Some(answer) = block.find(WAKEUP_HEAD).map(|start| &block[start..]) else {
1331            continue;
1332        };
1333        let Some((briefing, _)) = answer.rsplit_once(WAKEUP_HASH_LINE) else {
1334            continue;
1335        };
1336        let hash = wakeup_hash(briefing);
1337        if !answer.starts_with(&wakeup_full(briefing, &hash)) {
1338            continue;
1339        }
1340        let entry = (holder.to_string(), hash);
1341        // Not recorded within the lock bound: the next wake-up is answered in full.
1342        let Some(mut released) = crate::server::bounded_lock::write(
1343            wakeup_releases(),
1344            "ctx_knowledge wakeup release write",
1345        ) else {
1346            return;
1347        };
1348        if !released.contains(&entry) {
1349            if released.len() == REMEMBERED {
1350                released.remove(0);
1351            }
1352            released.push(entry);
1353        }
1354    }
1355}