Skip to main content

lean_ctx_server/tools/ctx_knowledge/
mod.rs

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