Skip to main content

lean_ctx_server/tools/registered/
ctx_knowledge.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7    McpTool, ToolContext, ToolOutput, get_f64, get_str, get_str_array,
8};
9use lean_ctx::tool_defs::tool_def;
10
11pub struct CtxKnowledgeTool;
12
13impl McpTool for CtxKnowledgeTool {
14    fn name(&self) -> &'static str {
15        "ctx_knowledge"
16    }
17
18    fn tool_def(&self) -> Tool {
19        tool_def(
20            "ctx_knowledge",
21            "Persistent memory across sessions — remember decisions, patterns, and facts for recall.\n\
22             WORKFLOW: save after completing significant tasks; recall at session start.\n\
23             action=remember value='Y' saves a fact (key optional — derived from value; content= is an accepted alias).\n\
24             action=recall query='X' retrieves it (bare recall lists recent facts). action=status shows all categories.\n\
25action=consolidate imports latest session if present, runs lifecycle, then frees 25% history/patterns capacity.\n\
26             action=gotcha trigger='X' resolution='Y' for known pitfalls.\n\
27             action=decisions [path=P|symbol=S] lists project decisions (.leanctx/decisions) in scope.\n\
28             mode=semantic|exact for recall. category groups related facts.",
29            json!({
30                "type": "object",
31                "properties": {
32                    "action": {
33                        "type": "string",
34                        "description": "remember|recall|search|pattern|gotcha|decisions|relate|relations|consolidate|restore|status|timeline|rooms|wakeup|remove|export|import (also: feedback, unrelate, relations_diagram, health, lifecycle_report, policy, embeddings_*; changes query=<lsn>|session, repin, coverage)"
35                    },
36                    "trigger": { "type": "string", "description": "gotcha trigger pattern" },
37                    "resolution": { "type": "string", "description": "gotcha resolution/fix" },
38                    "severity": { "type": "string", "description": "gotcha: critical|warning|info" },
39                    "category": { "type": "string", "description": "Fact category" },
40                    "key": { "type": "string" },
41                    "value": { "type": "string", "description": "remember/pattern: the text. wakeup (optional): the memory hash a full briefing ended with, only while that briefing is still in your context — answered \"unchanged\" only if exactly that briefing was released to a request of the same host presenter capability; in every other case the full briefing is returned" },
42                    "content": { "type": "string", "description": "Alias for value (remember)" },
43                    "sources": { "type": "array", "items": { "type": "string" }, "description": "remember: project files the fact is derived from (read now and bound to it)" },
44                    "anchors": { "type": "array", "items": { "type": "string" }, "description": "remember: code the fact is about, path or path::symbol (max 16); a later change there marks the fact to verify" },
45                    "type": { "type": "string", "description": "remember: fact|decision|gotcha|procedure|finding (Hive capture)" },
46                    "refs": { "type": "array", "items": { "type": "string" }, "description": "remember: references for Hive capture (max 10): file:<path>[#L<a>-<b>], sym:<path>#<symbol>, test:<path>::<name>, commit:<sha>, https://…" },
47                    "evidence": { "type": "string", "description": "remember: observed|stated|imported" },
48                    "steps": { "type": "array", "items": { "type": "string" }, "description": "remember type=procedure: steps (value = title)" },
49                    "commands": { "type": "array", "items": { "type": "object", "properties": { "shell": { "type": "string" }, "cmd": { "type": "string" }, "cwd_hint": { "type": "string" } }, "required": ["shell", "cmd"] }, "description": "remember type=procedure: commands as data (never executed)" },
50                    "validity": { "type": "string", "description": "remember: convention (project rule, shared with linked checkouts regardless of revision) | content (bound to its sources' revision). Default: convention for category convention/decision, content when sources bind" },
51                    "query": { "type": "string", "description": "Query for recall/search/relate/restore" },
52                    "mode": { "type": "string", "description": "auto|exact|semantic|hybrid" },
53                    "as_of": { "type": "string", "description": "YYYY-MM-DD date filter" },
54                    "pattern_type": { "type": "string" },
55                    "examples": { "type": "array", "items": { "type": "string" } },
56                    "confidence": { "type": "number", "description": "0.0-1.0" },
57                    "store": { "type": "string", "description": "restore: facts|history|patterns (default: all)" },
58                    "limit": { "type": "number", "description": "restore: max items to recover (default 50). recall with category: facts per window (default memory.knowledge.recall_facts_limit, max 200)" },
59                    "offset": { "type": "number", "description": "recall with category: facts to skip, to page past the limit (default 0)" },
60                    "dry_run": { "type": "boolean", "description": "consolidate: preview imports/reclaim without writing" },
61                    "format": { "type": "string", "description": "export: json|okf (okf = portable Markdown bundle)" },
62                    "path": { "type": "string", "description": "export/import: bundle directory (OKF) or file path; decisions: file whose in-scope decisions to list" },
63                    "symbol": { "type": "string", "description": "decisions: symbol (name or path::name) whose decisions to list" },
64                    "merge": { "type": "string", "description": "import: replace|append|skip-existing (default skip-existing)" }
65                },
66                "allOf": [
67                    {
68                        "if": { "properties": { "action": { "const": "remember" } }, "required": ["action"] },
69                        "then": { "required": ["category"], "anyOf": [{ "required": ["value"] }, { "required": ["content"] }] }
70                    },
71                    {
72                        "if": { "properties": { "action": { "const": "pattern" } }, "required": ["action"] },
73                        "then": { "required": ["value"] }
74                    },
75                    {
76                        "if": { "properties": { "action": { "const": "search" } }, "required": ["action"] },
77                        "then": { "required": ["query"] }
78                    },
79                    {
80                        "if": { "properties": { "action": { "const": "gotcha" } }, "required": ["action"] },
81                        "then": { "required": ["trigger", "resolution"] }
82                    }
83                ],
84                "required": ["action"]
85            }),
86        )
87    }
88
89    fn handle(
90        &self,
91        args: &Map<String, Value>,
92        ctx: &ToolContext,
93    ) -> Result<ToolOutput, ErrorData> {
94        let action = get_str(args, "action")
95            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
96        let category = get_str(args, "category");
97        let key = get_str(args, "key");
98        // `content` is the wording our own workflow docs use for remember;
99        // accept it as an alias so agents following those docs succeed (#658).
100        let value = get_str(args, "value").or_else(|| get_str(args, "content"));
101        let query = get_str(args, "query");
102        let mode = get_str(args, "mode");
103        let as_of = get_str(args, "as_of");
104        let pattern_type = get_str(args, "pattern_type");
105        let examples = get_str_array(args, "examples");
106        let confidence = get_f64(args, "confidence").map(|v| v as f32);
107        let validity = match get_str(args, "validity") {
108            None => None,
109            Some(raw) => Some(
110                lean_ctx::core::knowledge::FactValidity::parse(&raw).ok_or_else(|| {
111                    ErrorData::invalid_params("validity must be convention or content", None)
112                })?,
113            ),
114        };
115
116        let session_handle = ctx
117            .session
118            .as_ref()
119            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
120        let (session_id, project_root) = {
121            let read_result =
122                crate::server::bounded_lock::read(session_handle, "ctx_knowledge session read");
123            if let Some(session) = read_result {
124                let sid = session.id.clone();
125                let root = session
126                    .project_root
127                    .clone()
128                    .unwrap_or_else(|| ctx.project_root.clone());
129                (sid, root)
130            } else {
131                tracing::warn!("ctx_knowledge: session read-lock timeout, using fallback");
132                ("unknown".to_string(), ctx.project_root.clone())
133            }
134        };
135
136        // Project decisions (`.leanctx/decisions/*.toml`): read-only query.
137        if action == "decisions" {
138            let text = lean_ctx::core::decisions::query_text(
139                std::path::Path::new(&project_root),
140                get_str(args, "path").as_deref(),
141                get_str(args, "symbol").as_deref(),
142            );
143            return Ok(text_output(&action, text));
144        }
145
146        if action == "gotcha" {
147            let trigger = get_str(args, "trigger").unwrap_or_default();
148            let resolution = get_str(args, "resolution").unwrap_or_default();
149            let severity = get_str(args, "severity").unwrap_or_default();
150            let cat = category.as_deref().unwrap_or("convention");
151
152            if trigger.is_empty() || resolution.is_empty() {
153                return Ok(text_output(
154                    &action,
155                    "ERROR: trigger and resolution are required for gotcha action".to_string(),
156                ));
157            }
158
159            let mut store = lean_ctx::core::gotcha_tracker::GotchaStore::load(&project_root);
160            let msg = match store.report_gotcha(&trigger, &resolution, cat, &severity, &session_id)
161            {
162                Some(gotcha) => {
163                    let conf = (gotcha.confidence * 100.0) as u32;
164                    let label = gotcha.category.short_label();
165                    format!("Gotcha recorded: [{label}] {trigger} (confidence: {conf}%)")
166                }
167                None => {
168                    format!("Gotcha noted: {trigger} (evicted by higher-confidence entries)")
169                }
170            };
171            let _ = store.save(&project_root);
172            return Ok(text_output(&action, msg));
173        }
174
175        // Restore (#995 Phase 6): explicit cross-store undo from archive. Handled
176        // inline (like `gotcha`) so `store`/`limit` can be passed without widening
177        // the shared `handle()` signature.
178        if action == "restore" {
179            let store = match get_str(args, "store").as_deref() {
180                Some(s) if lean_ctx::core::memory_archive::MemoryStore::is_retired(s) => {
181                    return Ok(text_output(
182                        &action,
183                        lean_ctx::core::memory_archive::RETIRED_PROCEDURES_STORE_NOTICE.to_string(),
184                    ));
185                }
186                Some(s) => match lean_ctx::core::memory_archive::MemoryStore::parse(s) {
187                    Some(ms) => Some(ms),
188                    None => {
189                        return Ok(text_output(
190                            &action,
191                            format!("Unknown store: {s}. Use: facts, history, patterns"),
192                        ));
193                    }
194                },
195                None => None,
196            };
197            let limit = get_f64(args, "limit")
198                .map_or(crate::tools::ctx_knowledge::DEFAULT_RESTORE_LIMIT, |v| {
199                    v as usize
200                });
201            let opts =
202                crate::tools::ctx_knowledge::RestoreOptions::new(store, query.clone(), limit);
203            let text = match crate::tools::ctx_knowledge::run_restore(&project_root, &opts) {
204                Ok(report) => crate::tools::ctx_knowledge::format_restore_report(&report),
205                Err(e) => e,
206            };
207            return Ok(text_output(&action, text));
208        }
209
210        // Dry-run consolidate: preview imports + reclaim with no writes.
211        let dry_run = args
212            .get("dry_run")
213            .and_then(Value::as_bool)
214            .unwrap_or(false);
215        if action == "consolidate" && dry_run {
216            let text = match crate::tools::ctx_knowledge::consolidate_project_knowledge_with(
217                &project_root,
218                &lean_ctx::core::consolidation_engine::ConsolidateOptions::manual().into_dry_run(),
219            ) {
220                Ok(report) => crate::tools::ctx_knowledge::format_consolidation_report(&report),
221                Err(e) => e,
222            };
223            return Ok(text_output(&action, text));
224        }
225
226        // OKF export/import handled inline so `format`/`path`/`merge` stay off the
227        // shared handle() signature (same pattern as restore/gotcha above).
228        if action == "export" && get_str(args, "format").as_deref() == Some("okf") {
229            let out = match get_str(args, "path").or_else(|| get_str(args, "output")) {
230                Some(p) => match jailed_path("ctx_knowledge.export", &p, &project_root) {
231                    // Under a Workspace the authority confines it as well.
232                    Ok(p) => {
233                        match lean_ctx::core::workspace_authority::confine(&p, &project_root, true)
234                        {
235                            Ok(p) => Some(p),
236                            Err(error) => {
237                                return Ok(text_output(&action, format!("ERROR: {error}")));
238                            }
239                        }
240                    }
241                    Err(e) => return Ok(text_output(&action, e)),
242                },
243                None => None,
244            };
245            return Ok(text_output(
246                &action,
247                crate::tools::ctx_knowledge::handle_export_okf(&project_root, out.as_deref()),
248            ));
249        }
250        // Hive (#270): a write that moved the knowledge journal (remember,
251        // a conflict's fact update, forget, import …) is pushed to Hive
252        // from this process within about a second, off this call.
253        let journal_before = journal_head(&project_root);
254        if action == "import" {
255            let Some(path) = get_str(args, "path").or_else(|| query.clone()) else {
256                return Ok(text_output(
257                    &action,
258                    "ERROR: import requires `path` (a file or an OKF directory)".to_string(),
259                ));
260            };
261            let path =
262                match jailed_path("ctx_knowledge.import", &path, &project_root).and_then(|p| {
263                    // Under a Workspace the authority confines it as well.
264                    lean_ctx::core::workspace_authority::confine(&p, &project_root, false)
265                        .map_err(|error| format!("ERROR: {error}"))
266                }) {
267                    Ok(p) => p,
268                    Err(e) => return Ok(text_output(&action, e)),
269                };
270            let merge = get_str(args, "merge")
271                .and_then(|s| lean_ctx::core::knowledge::ImportMerge::parse(&s))
272                .unwrap_or(lean_ctx::core::knowledge::ImportMerge::SkipExisting);
273            let text = crate::tools::ctx_knowledge::handle_import(
274                &project_root,
275                &path,
276                merge,
277                &session_id,
278            );
279            push_if_written(&project_root, journal_before);
280            return Ok(text_output(&action, text));
281        }
282
283        // A typed failure (every failure of the declaring actions `recall`,
284        // `timeline`, `search`, and the refusals all actions share) is a tool
285        // error with the same text — never a reply that could be recorded as
286        // a delivery of the sources captured before it failed.
287        // #2248: a category listing's window (`limit` bounded in the handler).
288        let window = crate::tools::ctx_knowledge::RecallWindow::new(
289            get_f64(args, "limit").map(|v| v as usize),
290            get_f64(args, "offset").map(|v| v as usize),
291        );
292        let outcome = crate::tools::ctx_knowledge::handle_outcome_windowed(
293            &project_root,
294            &action,
295            category.as_deref(),
296            key.as_deref(),
297            value.as_deref(),
298            query.as_deref(),
299            &session_id,
300            pattern_type.as_deref(),
301            examples,
302            confidence,
303            mode.as_deref(),
304            as_of.as_deref(),
305            window,
306        );
307        let failed = outcome.is_err();
308        let (Ok(result) | Err(result)) = outcome;
309        let named = get_str_array(args, "sources").unwrap_or_default();
310        let result = if action == "remember" && !failed {
311            remembered_with(
312                result,
313                &project_root,
314                category.as_deref(),
315                key.as_deref(),
316                value.as_deref(),
317                &named,
318                validity,
319            )
320        } else {
321            result
322        };
323        // J2: anchors to the code the fact is about, all or none.
324        let anchors = get_str_array(args, "anchors").unwrap_or_default();
325        let result = match (
326            action == "remember" && !failed && !anchors.is_empty(),
327            category.as_deref(),
328            value.as_deref(),
329        ) {
330            (true, Some(category), Some(value)) => {
331                match crate::tools::ctx_knowledge::anchor_remembered(
332                    &project_root,
333                    category,
334                    key.as_deref(),
335                    value,
336                    &anchors,
337                ) {
338                    Ok(set) => format!("{result}\nanchors: {} recorded", set.len()),
339                    Err(reason) => {
340                        format!("{result}\nanchors: not recorded ({reason}); the fact has none")
341                    }
342                }
343            }
344            _ => result,
345        };
346        // Hive capture fields (v4 V1), all or none.
347        let result = match (
348            action == "remember" && !failed,
349            category.as_deref(),
350            value.as_deref(),
351        ) {
352            (true, Some(category), Some(value)) => match capture_fields(args) {
353                Ok(None) => result,
354                Ok(Some(fields)) => match crate::tools::ctx_knowledge::capture_remembered(
355                    &project_root,
356                    category,
357                    key.as_deref(),
358                    value,
359                    fields,
360                ) {
361                    Ok(()) => format!("{result}\ncapture: recorded"),
362                    Err(reason) => format!("{result}\ncapture: not recorded ({reason})"),
363                },
364                Err(reason) => format!("{result}\ncapture: not recorded ({reason})"),
365            },
366            _ => result,
367        };
368        // Hive: whether the fact goes to the team, or stays local and why
369        // (the capture gate's rules, checked now instead of at sync).
370        let result = match (action == "remember" && !failed, value.as_deref()) {
371            (true, Some(value)) => {
372                let has_ref = get_str_array(args, "refs").is_some_and(|r| !r.is_empty())
373                    || !anchors.is_empty();
374                match lean_ctx_hive::capture::sharing::note(&project_root, value, has_ref) {
375                    Some(line) => format!("{result}\nhive: {line}"),
376                    None => result,
377                }
378            }
379            _ => result,
380        };
381        push_if_written(&project_root, journal_before);
382
383        if failed {
384            return Err(crate::server::tool_trait::tool_execution_error(result));
385        }
386        Ok(text_output(&action, result))
387    }
388
389    /// Declared for `recall`, `timeline` and `search`. Their replies are
390    /// fixed text, the request's own arguments, and stored facts with their
391    /// identity and counters; every fact passes
392    /// `ctx_knowledge::fact_served`, which publishes the files of a fact
393    /// bound to sources and marks the capture incomplete for a fact without
394    /// a binding. A judgement line under a recalled fact marks it too.
395    /// `search` adds session entries only as the originless rule serves
396    /// them, which is never while protection is active.
397    ///
398    /// Not declared: `remember` (echoes the value and previews similar
399    /// facts), `status`, `wakeup` and `export` (rendered by the knowledge
400    /// store, which consults no binding), `relations*`, `restore`,
401    /// `consolidate*`, `gotcha`, `pattern`, the bridge and embeddings
402    /// actions (other stores or no fact value), and the rest (no stored
403    /// fact in the reply).
404    fn publishes_every_source(&self, args: Option<&Map<String, Value>>) -> bool {
405        matches!(
406            args.and_then(|args| get_str(args, "action")).as_deref(),
407            Some("recall" | "timeline" | "search")
408        )
409    }
410}
411
412/// The newest LSN of the knowledge journal of `project_root`.
413fn journal_head(project_root: &str) -> Option<u64> {
414    lean_ctx::core::knowledge::knowledge_dir_of(project_root)
415        .ok()
416        .map(|dir| lean_ctx::core::knowledge::journal::head_lsn(&dir))
417}
418
419/// Push the vault of `project_root` to Hive soon when the journal moved
420/// past `before` (the head before the action ran).
421fn push_if_written(project_root: &str, before: Option<u64>) {
422    if before.is_some() && journal_head(project_root) != before {
423        lean_ctx_hive::sync::on_write::push_soon(project_root);
424    }
425}
426
427/// The capture fields a `remember` names; `None` when it names none.
428fn capture_fields(
429    args: &Map<String, Value>,
430) -> Result<Option<lean_ctx::core::knowledge::FactCapture>, String> {
431    use lean_ctx::core::knowledge::{EvidenceLevel, FactCapture, NodeType, ProcedureCommand};
432    let node_type = get_str(args, "type")
433        .map(|t| NodeType::parse(&t).ok_or_else(|| format!("type {t:?}: not a node type")))
434        .transpose()?;
435    let evidence = get_str(args, "evidence")
436        .map(|e| EvidenceLevel::parse(&e).ok_or_else(|| format!("evidence {e:?}: not a level")))
437        .transpose()?;
438    let commands: Vec<ProcedureCommand> = match args.get("commands") {
439        Some(v) => serde_json::from_value(v.clone()).map_err(|e| format!("commands: {e}"))?,
440        None => Vec::new(),
441    };
442    let fields = FactCapture {
443        node_type,
444        steps: get_str_array(args, "steps").unwrap_or_default(),
445        commands,
446        refs: get_str_array(args, "refs").unwrap_or_default(),
447        evidence,
448        changed_at: None,
449    };
450    Ok((fields != FactCapture::default()).then_some(fields))
451}
452
453const SOURCES_BOUND: &str = "sources: bound to the fact";
454const SOURCES_NOT_BOUND: &str = "sources: not bound (a named source is not an admitted project file, or the fact was not stored as given); the fact has no source binding";
455const SOURCES_NOT_BOUND_CONVENTION: &str =
456    "sources: not bound (a convention is not bound to a revision)";
457
458/// The `remember` reply with what this call recorded beyond the fact: the
459/// source binding (`sources`) and the validity class (AP01 §4). An explicit
460/// `validity` wins; a fact that names sources is `content`. A
461/// convention is never bound to sources — it is shared regardless of
462/// revision, so a revision must not decide whether it is served.
463fn remembered_with(
464    reply: String,
465    project_root: &str,
466    category: Option<&str>,
467    key: Option<&str>,
468    value: Option<&str>,
469    named: &[String],
470    validity: Option<lean_ctx::core::knowledge::FactValidity>,
471) -> String {
472    use lean_ctx::core::knowledge::FactValidity;
473    let mut reply = reply;
474    if !named.is_empty() {
475        let line = if validity == Some(FactValidity::Convention) {
476            SOURCES_NOT_BOUND_CONVENTION
477        } else if bind_remembered(project_root, category, key, value, named) {
478            SOURCES_BOUND
479        } else {
480            SOURCES_NOT_BOUND
481        };
482        reply = format!("{reply}\n{line}");
483    }
484    // A fact that names files is about code at a revision, bound or not: an
485    // unbound one is then never served where its files cannot be checked.
486    let class = validity.or((!named.is_empty()).then_some(FactValidity::Content));
487    if let (Some(class), Some(category), Some(value)) = (class, category, value)
488        && crate::tools::ctx_knowledge::classify_remembered(
489            project_root,
490            category,
491            key,
492            value,
493            class,
494        )
495    {
496        reply = format!("{reply}\nvalidity: {}", class.as_str());
497    }
498    reply
499}
500
501/// Bind the fact a `remember` has just stored to the `sources` its writer
502/// named. Each is read now through the admitted reader; the fact is bound to
503/// all of them or to none (`archive::bindings`). Bound is only the fact that
504/// carries exactly the value of this call — never an older value under the
505/// same key, and never a value the store merged, rewrote or rejected.
506fn bind_remembered(
507    project_root: &str,
508    category: Option<&str>,
509    key: Option<&str>,
510    value: Option<&str>,
511    sources: &[String],
512) -> bool {
513    use lean_ctx::core::archive::bindings::{self, Item};
514    let (Some(category), Some(value)) = (category, value) else {
515        return false;
516    };
517    let Some(knowledge) = lean_ctx::core::knowledge::ProjectKnowledge::load(project_root) else {
518        return false;
519    };
520    let Some(fact) = knowledge.facts.iter().rev().find(|fact| {
521        fact.is_current()
522            && fact.category == category
523            && fact.value == value
524            && key.is_none_or(|key| fact.key == key)
525    }) else {
526        return false;
527    };
528    let Some(sources) = bindings::sources_at(project_root, sources, "ctx_knowledge") else {
529        return false;
530    };
531    let item = Item::KnowledgeFact {
532        project: project_root,
533        category: &fact.category,
534        key: &fact.key,
535    };
536    bindings::bind(&item, &fact.value, project_root, sources)
537}
538
539/// OKF export/import take a caller-supplied `path`. Like ctx_read and
540/// ctx_handoff, keep it inside the project jail; a relative path is taken from
541/// the project root.
542fn jailed_path(tool: &str, raw: &str, project_root: &str) -> Result<String, String> {
543    let root = std::path::Path::new(project_root);
544    let candidate = std::path::Path::new(raw);
545    let candidate = if candidate.is_absolute() {
546        candidate.to_path_buf()
547    } else {
548        root.join(candidate)
549    };
550    lean_ctx::core::io_boundary::jail_and_check_path(tool, &candidate, root)
551        .map(|(p, _warning)| p.to_string_lossy().into_owned())
552}
553
554/// A plain text `ToolOutput` tagged with the action as its mode. `ctx_knowledge`
555/// results are already compressed prose, so token accounting is left at zero.
556fn text_output(action: &str, text: String) -> ToolOutput {
557    ToolOutput {
558        text,
559        original_tokens: 0,
560        saved_tokens: 0,
561        mode: Some(action.to_string()),
562        path: None,
563        changed: false,
564        shell_outcome: None,
565        content_blocks: None,
566    }
567}
568
569#[cfg(test)]
570mod source_binding_tests {
571    use super::*;
572    use lean_ctx::core::archive::bindings::{self, Item};
573    use lean_ctx::core::context_admission::stored::lineage_support::{
574        deliver, governed, project, reusable,
575    };
576
577    fn remember(root: &str, key: &str, value: &str) {
578        let reply = crate::tools::ctx_knowledge::handle(
579            root,
580            "remember",
581            Some("architecture"),
582            Some(key),
583            Some(value),
584            None,
585            "session-1",
586            None,
587            None,
588            None,
589            None,
590            None,
591        );
592        assert!(!reply.starts_with("ERROR"), "{reply}");
593    }
594
595    /// `remember` with a readable source binds the stored fact; with a source
596    /// that is not admitted, or for a value other than the stored one, the
597    /// fact stays stored and originless.
598    #[test]
599    fn remember_binds_the_stored_fact_to_the_sources_named_with_it() {
600        let _data = governed();
601        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
602        let (_directory, root) = project();
603        std::fs::write(format!("{root}/auth.rs"), "pub fn verify_rs256() {}\n").expect("source");
604        std::fs::write(format!("{root}/plan.md"), "*** TOP SECRET ***\nlaunch\n").expect("marked");
605        let value = "Tokens are verified with RS256 in the auth module";
606        remember(&root, "token-check", value);
607        let key = |sources: &[&str]| {
608            let sources: Vec<String> = sources.iter().map(|path| (*path).to_owned()).collect();
609            bind_remembered(
610                &root,
611                Some("architecture"),
612                Some("token-check"),
613                Some(value),
614                &sources,
615            )
616        };
617        assert!(!key(&["plan.md"]), "a restricted source binds nothing");
618        assert!(!key(&["auth.rs", "missing.rs"]), "all sources or none");
619        assert!(!bind_remembered(
620            &root,
621            Some("architecture"),
622            Some("token-check"),
623            Some("another value"),
624            &["auth.rs".to_owned()],
625        ));
626        let item = Item::KnowledgeFact {
627            project: &root,
628            category: "architecture",
629            key: "token-check",
630        };
631        let recall = || {
632            deliver(&root, || {
633                bindings::serve(&item, value, Some(&root)).expect("served");
634                format!("[architecture/token-check]: {value}")
635            })
636        };
637        assert_eq!(recall().1, 0, "stored, and originless so far");
638
639        assert!(key(&["auth.rs"]));
640        let (reply, recorded) = recall();
641        assert_eq!(recorded, 1);
642        assert_eq!(reusable(&root, &reply), Ok(()));
643    }
644
645    fn git(dir: &str, args: &[&str]) {
646        let status = std::process::Command::new("git")
647            .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
648            .args(args)
649            .current_dir(dir)
650            .env_remove("GIT_DIR")
651            .env_remove("GIT_WORK_TREE")
652            .status()
653            .expect("git runs");
654        assert!(status.success(), "git {args:?}");
655    }
656
657    /// S05 (AP01 §4): two worktrees of one repository, linked to one project
658    /// (D01). A convention is served in both regardless of branch. A fact
659    /// bound to `retry.rs` is served in its own worktree, withheld as stale
660    /// in the other while the file differs there on its branch, and served
661    /// there once the file is identical. An unclassified fact stays in its
662    /// own worktree, as before classes.
663    #[test]
664    fn linked_worktrees_share_conventions_and_withhold_stale_code() {
665        use lean_ctx::core::project_link::{ProjectLink, link, link_time};
666        let _data = governed();
667        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
668        let (_main_dir, main) = project();
669        let (_other_dir, other_parent) = project();
670        let feature = format!("{other_parent}/feature");
671        std::fs::write(format!("{main}/retry.rs"), "fn retry() { /* bounded */ }\n").unwrap();
672        git(&main, &["init", "-q", "-b", "main"]);
673        git(&main, &["add", "retry.rs"]);
674        git(&main, &["commit", "-q", "-m", "retry"]);
675        git(&main, &["worktree", "add", "-q", "-b", "feature", &feature]);
676        let feature = lean_ctx::core::pathutil::safe_canonicalize(std::path::Path::new(&feature))
677            .unwrap()
678            .to_str()
679            .unwrap()
680            .to_owned();
681        std::fs::write(format!("{feature}/retry.rs"), "fn retry() { loop {} }\n").unwrap();
682        git(&feature, &["commit", "-q", "-am", "unbounded"]);
683        for root in [&main, &feature] {
684            link(ProjectLink {
685                workspace_root: root.clone(),
686                team_project_id: "gateway".into(),
687                organization_id: None,
688                label: None,
689                linked_at: link_time(),
690            })
691            .unwrap();
692        }
693
694        let convention = "Branch names follow the pattern type slash slug";
695        let code = "The retry loop in retry.rs is bounded by its budget";
696        let local = "The release captain promotes deployments on Fridays";
697        let remember_in = |category: &str, key: &str, value: &str| {
698            let reply = crate::tools::ctx_knowledge::handle(
699                &main,
700                "remember",
701                Some(category),
702                Some(key),
703                Some(value),
704                None,
705                "session-1",
706                None,
707                None,
708                None,
709                None,
710                None,
711            );
712            assert!(reply.starts_with("Remembered"), "{reply}");
713        };
714        remember_in("decision", "branch-naming", convention);
715        remember_in("architecture", "retry-bound", code);
716        remember_in("architecture", "release-duty", local);
717        let reply = remembered_with(
718            String::new(),
719            &main,
720            Some("architecture"),
721            Some("retry-bound"),
722            Some(code),
723            &["retry.rs".to_owned()],
724            None,
725        );
726        assert!(reply.contains(SOURCES_BOUND), "{reply}");
727        assert!(reply.contains("validity: content"), "{reply}");
728
729        let recall = |root: &str| {
730            crate::tools::ctx_knowledge::handle(
731                root,
732                "recall",
733                None,
734                None,
735                None,
736                None,
737                "session-1",
738                None,
739                None,
740                None,
741                None,
742                None,
743            )
744        };
745        let own = recall(&main);
746        assert!(own.contains(&format!("{convention} (confidence")), "{own}");
747        assert!(own.contains("[convention]") && own.contains(code), "{own}");
748        assert!(own.contains(local), "{own}");
749
750        let linked = recall(&feature);
751        assert!(
752            linked.contains(&format!("{convention} [convention]")),
753            "{linked}"
754        );
755        assert!(!linked.contains(code), "{linked}");
756        assert!(
757            linked.contains("1 code-bound fact(s) withheld: stale"),
758            "{linked}"
759        );
760        assert!(!linked.contains(local), "{linked}");
761
762        std::fs::write(
763            format!("{feature}/retry.rs"),
764            "fn retry() { /* bounded */ }\n",
765        )
766        .unwrap();
767        let same = recall(&feature);
768        assert!(same.contains(&format!("{code} [content]")), "{same}");
769        assert!(!same.contains("withheld"), "{same}");
770    }
771
772    fn declares(action: &str) -> bool {
773        let mut args = Map::new();
774        args.insert("action".to_owned(), Value::String(action.to_owned()));
775        CtxKnowledgeTool.publishes_every_source(Some(&args))
776    }
777
778    /// The recall of the knowledge tool itself, as a declared action
779    /// delivers it.
780    fn recall(root: &str) -> (String, usize) {
781        deliver(root, || {
782            crate::tools::ctx_knowledge::handle(
783                root,
784                "recall",
785                Some("architecture"),
786                None,
787                None,
788                None,
789                "session-1",
790                None,
791                None,
792                None,
793                None,
794                None,
795            )
796        })
797    }
798
799    /// A fact remembered with sources and recalled by a declared action
800    /// gives the reply the lineage of its files. A fact without sources in
801    /// the same reply leaves it unknown. When a source is withheld by a
802    /// tightened rule, or deleted, the lineage refuses and the bound fact is
803    /// no longer recalled — the fact without sources still is.
804    #[test]
805    fn a_declared_recall_carries_the_lineage_of_its_bound_facts() {
806        use lean_ctx::core::archive::delivered::LineageRefusal;
807        let _data = governed();
808        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
809        let (_directory, root) = project();
810        std::fs::write(format!("{root}/auth.rs"), "pub fn verify_rs256() {}\n").expect("source");
811        let value = "Tokens are verified with RS256 in the auth module";
812        remember(&root, "token-check", value);
813        assert!(bind_remembered(
814            &root,
815            Some("architecture"),
816            Some("token-check"),
817            Some(value),
818            &["auth.rs".to_owned()],
819        ));
820        assert!(declares("recall") && declares("timeline") && declares("search"));
821        assert!(!declares("remember") && !declares("status") && !declares("wakeup"));
822
823        let (reply, recorded) = recall(&root);
824        assert!(reply.contains(value), "{reply}");
825        assert_eq!(recorded, 1);
826        assert_eq!(reusable(&root, &reply), Ok(()));
827
828        let typed = "Deployments are promoted by the release captain on Fridays";
829        remember(&root, "release-duty", typed);
830        let (mixed, recorded) = recall(&root);
831        assert!(mixed.contains(value) && mixed.contains(typed), "{mixed}");
832        assert_eq!(recorded, 0, "one fact without a source: unknown");
833        assert_eq!(reusable(&root, &mixed), Err(LineageRefusal::Unknown));
834
835        // The source is reclassified: the recorded reply is refused and the
836        // bound fact is left out of the next recall.
837        std::fs::write(
838            format!("{root}/auth.rs"),
839            "*** TOP SECRET ***\npub fn verify_rs256() {}\n",
840        )
841        .expect("mark");
842        assert_eq!(
843            reusable(&root, &reply),
844            Err(LineageRefusal::SourceNoLongerAdmitted)
845        );
846        let (withheld, recorded) = recall(&root);
847        assert!(!withheld.contains(value), "{withheld}");
848        assert!(withheld.contains(typed), "{withheld}");
849        assert_eq!(recorded, 0);
850
851        std::fs::remove_file(format!("{root}/auth.rs")).expect("delete");
852        assert_eq!(
853            reusable(&root, &reply),
854            Err(LineageRefusal::SourceNoLongerAdmitted)
855        );
856        assert!(!recall(&root).0.contains(value));
857    }
858}
859
860// The jail is the point of these tests; a `no-jail` build switches it off.
861#[cfg(all(test, not(feature = "no-jail")))]
862mod tests {
863    use super::*;
864
865    fn call(ctx: &ToolContext, args: &Value) -> String {
866        CtxKnowledgeTool
867            .handle(args.as_object().unwrap(), ctx)
868            .unwrap()
869            .text
870    }
871
872    #[test]
873    fn okf_export_and_import_paths_stay_in_the_project_jail() {
874        let _data = lean_ctx::core::data_dir::isolated_data_dir();
875        let root = tempfile::tempdir().unwrap();
876        let outside = tempfile::tempdir().unwrap();
877        let ctx = ToolContext {
878            project_root: root.path().to_string_lossy().into_owned(),
879            session: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
880                lean_ctx::core::session::SessionState::new(),
881            ))),
882            ..ToolContext::default()
883        };
884        call(
885            &ctx,
886            &json!({"action": "remember", "category": "architecture",
887                    "key": "parser", "value": "the parser is bounded"}),
888        );
889
890        let export_dir = outside.path().join("okf");
891        let text = call(
892            &ctx,
893            &json!({"action": "export", "format": "okf", "path": export_dir}),
894        );
895        assert!(!export_dir.exists(), "OKF export left the jail: {text}");
896
897        let facts = outside.path().join("facts.json");
898        std::fs::write(
899            &facts,
900            r#"[{"category":"secret","key":"outside","value":"OUTSIDE-JAIL"}]"#,
901        )
902        .unwrap();
903        let text = call(&ctx, &json!({"action": "import", "path": facts}));
904        assert!(
905            !text.contains("Import complete"),
906            "import read outside the jail: {text}"
907        );
908
909        let inside = root.path().join("okf-export");
910        let text = call(
911            &ctx,
912            &json!({"action": "export", "format": "okf", "path": inside}),
913        );
914        assert!(inside.join("index.md").exists(), "{text}");
915        let text = call(&ctx, &json!({"action": "import", "path": inside}));
916        assert!(text.contains("import"), "{text}");
917    }
918
919    /// #270: a fact `ctx_knowledge` remembers is handed to the push on write
920    /// of this process (which pushes the vault within about a second); a
921    /// read that writes nothing is not.
922    #[test]
923    fn a_remembered_fact_asks_for_a_push_and_a_recall_does_not() {
924        use lean_ctx_hive::sync::on_write::requested;
925        let _data = lean_ctx::core::data_dir::isolated_data_dir();
926        let dir = tempfile::tempdir().unwrap();
927        let root = dir
928            .path()
929            .canonicalize()
930            .unwrap()
931            .to_string_lossy()
932            .into_owned();
933        let ctx = ToolContext {
934            project_root: root.clone(),
935            session: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
936                lean_ctx::core::session::SessionState::new(),
937            ))),
938            ..ToolContext::default()
939        };
940        assert_eq!(requested(&root), 0);
941        call(
942            &ctx,
943            &json!({"action": "remember", "category": "architecture",
944                    "key": "retry", "value": "payments retry three times"}),
945        );
946        assert_eq!(requested(&root), 1, "the write asks for a push");
947        call(&ctx, &json!({"action": "recall", "query": "retry"}));
948        assert_eq!(requested(&root), 1, "a recall writes nothing");
949    }
950}