Skip to main content

lean_ctx/tools/ctx_knowledge/
mod.rs

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