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 reclaims full history/pattern stores losslessly.\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 (LeanCTX Cloud capture)" },
46                    "refs": { "type": "array", "items": { "type": "string" }, "description": "remember: references for LeanCTX Cloud 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        // Cloud (#270): a write that moved the knowledge journal (remember,
251        // a conflict's fact update, forget, import …) is pushed to Cloud
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        // `session.stats` `knowledge.written` (rel12 WP2): a remember that
310        // stored or reinforced a fact; a refusal or a low-salience skip
311        // wrote nothing.
312        if action == "remember"
313            && !failed
314            && remember_wrote(&result)
315            && let Some(mut session) =
316                crate::server::bounded_lock::write(session_handle, "ctx_knowledge written")
317        {
318            session.record_knowledge_written();
319        }
320        let named = get_str_array(args, "sources").unwrap_or_default();
321        let result = if action == "remember" && !failed {
322            remembered_with(
323                result,
324                &project_root,
325                category.as_deref(),
326                key.as_deref(),
327                value.as_deref(),
328                &named,
329                validity,
330            )
331        } else {
332            result
333        };
334        // J2: anchors to the code the fact is about, all or none.
335        let anchors = get_str_array(args, "anchors").unwrap_or_default();
336        let result = match (
337            action == "remember" && !failed && !anchors.is_empty(),
338            category.as_deref(),
339            value.as_deref(),
340        ) {
341            (true, Some(category), Some(value)) => {
342                match crate::tools::ctx_knowledge::anchor_remembered(
343                    &project_root,
344                    category,
345                    key.as_deref(),
346                    value,
347                    &anchors,
348                ) {
349                    Ok(set) => format!("{result}\nanchors: {} recorded", set.len()),
350                    Err(reason) => {
351                        format!("{result}\nanchors: not recorded ({reason}); the fact has none")
352                    }
353                }
354            }
355            _ => result,
356        };
357        // Cloud capture fields (v4 V1), all or none.
358        let result = match (
359            action == "remember" && !failed,
360            category.as_deref(),
361            value.as_deref(),
362        ) {
363            (true, Some(category), Some(value)) => match capture_fields(args) {
364                Ok(None) => result,
365                Ok(Some(fields)) => match crate::tools::ctx_knowledge::capture_remembered(
366                    &project_root,
367                    category,
368                    key.as_deref(),
369                    value,
370                    fields,
371                ) {
372                    Ok(()) => format!("{result}\ncapture: recorded"),
373                    Err(reason) => format!("{result}\ncapture: not recorded ({reason})"),
374                },
375                Err(reason) => format!("{result}\ncapture: not recorded ({reason})"),
376            },
377            _ => result,
378        };
379        // Cloud: whether the fact goes to the team, or stays local and why
380        // (the capture gate's rules, checked now instead of at sync).
381        let result = match (action == "remember" && !failed, value.as_deref()) {
382            (true, Some(value)) => {
383                let has_ref = get_str_array(args, "refs").is_some_and(|r| !r.is_empty())
384                    || !anchors.is_empty();
385                match lean_ctx_cloud::capture::sharing::note(&project_root, value, has_ref) {
386                    Some(line) => format!("{result}\ncloud: {line}"),
387                    None => result,
388                }
389            }
390            _ => result,
391        };
392        push_if_written(&project_root, journal_before);
393
394        if failed {
395            return Err(crate::server::tool_trait::tool_execution_error(result));
396        }
397        Ok(text_output(&action, result))
398    }
399
400    /// Declared for `recall`, `timeline` and `search`. Their replies are
401    /// fixed text, the request's own arguments, and stored facts with their
402    /// identity and counters; every fact passes
403    /// `ctx_knowledge::fact_served`, which publishes the files of a fact
404    /// bound to sources and marks the capture incomplete for a fact without
405    /// a binding. A judgement line under a recalled fact marks it too.
406    /// `search` adds session entries only as the originless rule serves
407    /// them, which is never while protection is active.
408    ///
409    /// Not declared: `remember` (echoes the value and previews similar
410    /// facts), `status`, `wakeup` and `export` (rendered by the knowledge
411    /// store, which consults no binding), `relations*`, `restore`,
412    /// `consolidate*`, `gotcha`, `pattern`, the bridge and embeddings
413    /// actions (other stores or no fact value), and the rest (no stored
414    /// fact in the reply).
415    fn publishes_every_source(&self, args: Option<&Map<String, Value>>) -> bool {
416        matches!(
417            args.and_then(|args| get_str(args, "action")).as_deref(),
418            Some("recall" | "timeline" | "search")
419        )
420    }
421}
422
423/// Whether a `remember` reply reports a write. `handle_remember`
424/// (`ctx_knowledge/remember.rs`) answers every refusal with `Error: …` and a
425/// rejected low-salience fact (`AdmissionResult::RejectedLowSalience`) with
426/// `Skipped …`; a stored, revised, confirmed or merged fact starts otherwise.
427/// The admission result is not threaded through the shared text outcome of
428/// all actions, so the reply is read here; the tests in
429/// `session_stats_tests` pin both the counted and the refused replies.
430fn remember_wrote(reply: &str) -> bool {
431    !(reply.starts_with("Error") || reply.starts_with("Skipped "))
432}
433
434/// The newest LSN of the knowledge journal of `project_root`.
435fn journal_head(project_root: &str) -> Option<u64> {
436    lean_ctx::core::knowledge::knowledge_dir_of(project_root)
437        .ok()
438        .map(|dir| lean_ctx::core::knowledge::journal::head_lsn(&dir))
439}
440
441/// Push the vault of `project_root` to Cloud soon when the journal moved
442/// past `before` (the head before the action ran).
443fn push_if_written(project_root: &str, before: Option<u64>) {
444    if before.is_some() && journal_head(project_root) != before {
445        lean_ctx_cloud::sync::on_write::push_soon(project_root);
446    }
447}
448
449/// The capture fields a `remember` names; `None` when it names none.
450fn capture_fields(
451    args: &Map<String, Value>,
452) -> Result<Option<lean_ctx::core::knowledge::FactCapture>, String> {
453    use lean_ctx::core::knowledge::{EvidenceLevel, FactCapture, NodeType, ProcedureCommand};
454    let node_type = get_str(args, "type")
455        .map(|t| NodeType::parse(&t).ok_or_else(|| format!("type {t:?}: not a node type")))
456        .transpose()?;
457    let evidence = get_str(args, "evidence")
458        .map(|e| EvidenceLevel::parse(&e).ok_or_else(|| format!("evidence {e:?}: not a level")))
459        .transpose()?;
460    let commands: Vec<ProcedureCommand> = match args.get("commands") {
461        Some(v) => serde_json::from_value(v.clone()).map_err(|e| format!("commands: {e}"))?,
462        None => Vec::new(),
463    };
464    let fields = FactCapture {
465        node_type,
466        steps: get_str_array(args, "steps").unwrap_or_default(),
467        commands,
468        refs: get_str_array(args, "refs").unwrap_or_default(),
469        evidence,
470        changed_at: None,
471    };
472    Ok((fields != FactCapture::default()).then_some(fields))
473}
474
475const SOURCES_BOUND: &str = "sources: bound to the fact";
476const 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";
477const SOURCES_NOT_BOUND_CONVENTION: &str =
478    "sources: not bound (a convention is not bound to a revision)";
479
480/// The `remember` reply with what this call recorded beyond the fact: the
481/// source binding (`sources`) and the validity class (AP01 §4). An explicit
482/// `validity` wins; a fact that names sources is `content`. A
483/// convention is never bound to sources — it is shared regardless of
484/// revision, so a revision must not decide whether it is served.
485fn remembered_with(
486    reply: String,
487    project_root: &str,
488    category: Option<&str>,
489    key: Option<&str>,
490    value: Option<&str>,
491    named: &[String],
492    validity: Option<lean_ctx::core::knowledge::FactValidity>,
493) -> String {
494    use lean_ctx::core::knowledge::FactValidity;
495    let mut reply = reply;
496    if !named.is_empty() {
497        let line = if validity == Some(FactValidity::Convention) {
498            SOURCES_NOT_BOUND_CONVENTION
499        } else if bind_remembered(project_root, category, key, value, named) {
500            SOURCES_BOUND
501        } else {
502            SOURCES_NOT_BOUND
503        };
504        reply = format!("{reply}\n{line}");
505    }
506    // A fact that names files is about code at a revision, bound or not: an
507    // unbound one is then never served where its files cannot be checked.
508    let class = validity.or((!named.is_empty()).then_some(FactValidity::Content));
509    if let (Some(class), Some(category), Some(value)) = (class, category, value)
510        && crate::tools::ctx_knowledge::classify_remembered(
511            project_root,
512            category,
513            key,
514            value,
515            class,
516        )
517    {
518        reply = format!("{reply}\nvalidity: {}", class.as_str());
519    }
520    reply
521}
522
523/// Bind the fact a `remember` has just stored to the `sources` its writer
524/// named. Each is read now through the admitted reader; the fact is bound to
525/// all of them or to none (`archive::bindings`). Bound is only the fact that
526/// carries exactly the value of this call — never an older value under the
527/// same key, and never a value the store merged, rewrote or rejected.
528fn bind_remembered(
529    project_root: &str,
530    category: Option<&str>,
531    key: Option<&str>,
532    value: Option<&str>,
533    sources: &[String],
534) -> bool {
535    use lean_ctx::core::archive::bindings::{self, Item};
536    let (Some(category), Some(value)) = (category, value) else {
537        return false;
538    };
539    let Some(knowledge) = lean_ctx::core::knowledge::ProjectKnowledge::load(project_root) else {
540        return false;
541    };
542    let Some(fact) = knowledge.facts.iter().rev().find(|fact| {
543        fact.is_current()
544            && fact.category == category
545            && fact.value == value
546            && key.is_none_or(|key| fact.key == key)
547    }) else {
548        return false;
549    };
550    let Some(sources) = bindings::sources_at(project_root, sources, "ctx_knowledge") else {
551        return false;
552    };
553    let item = Item::KnowledgeFact {
554        project: project_root,
555        category: &fact.category,
556        key: &fact.key,
557    };
558    bindings::bind(&item, &fact.value, project_root, sources)
559}
560
561/// OKF export/import take a caller-supplied `path`. Like ctx_read and
562/// ctx_handoff, keep it inside the project jail; a relative path is taken from
563/// the project root.
564fn jailed_path(tool: &str, raw: &str, project_root: &str) -> Result<String, String> {
565    let root = std::path::Path::new(project_root);
566    let candidate = std::path::Path::new(raw);
567    let candidate = if candidate.is_absolute() {
568        candidate.to_path_buf()
569    } else {
570        root.join(candidate)
571    };
572    lean_ctx::core::io_boundary::jail_and_check_path(tool, &candidate, root)
573        .map(|(p, _warning)| p.to_string_lossy().into_owned())
574}
575
576/// A plain text `ToolOutput` tagged with the action as its mode. `ctx_knowledge`
577/// results are already compressed prose, so token accounting is left at zero.
578fn text_output(action: &str, text: String) -> ToolOutput {
579    ToolOutput {
580        text,
581        original_tokens: 0,
582        saved_tokens: 0,
583        mode: Some(action.to_string()),
584        path: None,
585        changed: false,
586        shell_outcome: None,
587        content_blocks: None,
588    }
589}
590
591#[cfg(test)]
592mod source_binding_tests {
593    use super::*;
594    use lean_ctx::core::archive::bindings::{self, Item};
595    use lean_ctx::core::context_admission::stored::lineage_support::{
596        deliver, governed, project, reusable,
597    };
598
599    fn remember(root: &str, key: &str, value: &str) {
600        let reply = crate::tools::ctx_knowledge::handle(
601            root,
602            "remember",
603            Some("architecture"),
604            Some(key),
605            Some(value),
606            None,
607            "session-1",
608            None,
609            None,
610            None,
611            None,
612            None,
613        );
614        assert!(!reply.starts_with("ERROR"), "{reply}");
615    }
616
617    /// `remember` with a readable source binds the stored fact; with a source
618    /// that is not admitted, or for a value other than the stored one, the
619    /// fact stays stored and originless.
620    #[test]
621    fn remember_binds_the_stored_fact_to_the_sources_named_with_it() {
622        let _data = governed();
623        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
624        let (_directory, root) = project();
625        std::fs::write(format!("{root}/auth.rs"), "pub fn verify_rs256() {}\n").expect("source");
626        std::fs::write(format!("{root}/plan.md"), "*** TOP SECRET ***\nlaunch\n").expect("marked");
627        let value = "Tokens are verified with RS256 in the auth module";
628        remember(&root, "token-check", value);
629        let key = |sources: &[&str]| {
630            let sources: Vec<String> = sources.iter().map(|path| (*path).to_owned()).collect();
631            bind_remembered(
632                &root,
633                Some("architecture"),
634                Some("token-check"),
635                Some(value),
636                &sources,
637            )
638        };
639        assert!(!key(&["plan.md"]), "a restricted source binds nothing");
640        assert!(!key(&["auth.rs", "missing.rs"]), "all sources or none");
641        assert!(!bind_remembered(
642            &root,
643            Some("architecture"),
644            Some("token-check"),
645            Some("another value"),
646            &["auth.rs".to_owned()],
647        ));
648        let item = Item::KnowledgeFact {
649            project: &root,
650            category: "architecture",
651            key: "token-check",
652        };
653        let recall = || {
654            deliver(&root, || {
655                bindings::serve(&item, value, Some(&root)).expect("served");
656                format!("[architecture/token-check]: {value}")
657            })
658        };
659        assert_eq!(recall().1, 0, "stored, and originless so far");
660
661        assert!(key(&["auth.rs"]));
662        let (reply, recorded) = recall();
663        assert_eq!(recorded, 1);
664        assert_eq!(reusable(&root, &reply), Ok(()));
665    }
666
667    fn git(dir: &str, args: &[&str]) {
668        let status = std::process::Command::new("git")
669            .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
670            .args(args)
671            .current_dir(dir)
672            .env_remove("GIT_DIR")
673            .env_remove("GIT_WORK_TREE")
674            .status()
675            .expect("git runs");
676        assert!(status.success(), "git {args:?}");
677    }
678
679    /// S05 (AP01 §4): two worktrees of one repository, linked to one project
680    /// (D01). A convention is served in both regardless of branch. A fact
681    /// bound to `retry.rs` is served in its own worktree, withheld as stale
682    /// in the other while the file differs there on its branch, and served
683    /// there once the file is identical. An unclassified fact stays in its
684    /// own worktree, as before classes.
685    #[test]
686    fn linked_worktrees_share_conventions_and_withhold_stale_code() {
687        use lean_ctx::core::project_link::{ProjectLink, link, link_time};
688        let _data = governed();
689        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
690        let (_main_dir, main) = project();
691        let (_other_dir, other_parent) = project();
692        let feature = format!("{other_parent}/feature");
693        std::fs::write(format!("{main}/retry.rs"), "fn retry() { /* bounded */ }\n").unwrap();
694        git(&main, &["init", "-q", "-b", "main"]);
695        git(&main, &["add", "retry.rs"]);
696        git(&main, &["commit", "-q", "-m", "retry"]);
697        git(&main, &["worktree", "add", "-q", "-b", "feature", &feature]);
698        let feature = lean_ctx::core::pathutil::safe_canonicalize(std::path::Path::new(&feature))
699            .unwrap()
700            .to_str()
701            .unwrap()
702            .to_owned();
703        std::fs::write(format!("{feature}/retry.rs"), "fn retry() { loop {} }\n").unwrap();
704        git(&feature, &["commit", "-q", "-am", "unbounded"]);
705        for root in [&main, &feature] {
706            link(ProjectLink {
707                workspace_root: root.clone(),
708                team_project_id: "gateway".into(),
709                organization_id: None,
710                label: None,
711                linked_at: link_time(),
712            })
713            .unwrap();
714        }
715
716        let convention = "Branch names follow the pattern type slash slug";
717        let code = "The retry loop in retry.rs is bounded by its budget";
718        let local = "The release captain promotes deployments on Fridays";
719        let remember_in = |category: &str, key: &str, value: &str| {
720            let reply = crate::tools::ctx_knowledge::handle(
721                &main,
722                "remember",
723                Some(category),
724                Some(key),
725                Some(value),
726                None,
727                "session-1",
728                None,
729                None,
730                None,
731                None,
732                None,
733            );
734            assert!(reply.starts_with("Remembered"), "{reply}");
735        };
736        remember_in("decision", "branch-naming", convention);
737        remember_in("architecture", "retry-bound", code);
738        remember_in("architecture", "release-duty", local);
739        let reply = remembered_with(
740            String::new(),
741            &main,
742            Some("architecture"),
743            Some("retry-bound"),
744            Some(code),
745            &["retry.rs".to_owned()],
746            None,
747        );
748        assert!(reply.contains(SOURCES_BOUND), "{reply}");
749        assert!(reply.contains("validity: content"), "{reply}");
750
751        let recall = |root: &str| {
752            crate::tools::ctx_knowledge::handle(
753                root,
754                "recall",
755                None,
756                None,
757                None,
758                None,
759                "session-1",
760                None,
761                None,
762                None,
763                None,
764                None,
765            )
766        };
767        let own = recall(&main);
768        assert!(own.contains(&format!("{convention} (confidence")), "{own}");
769        assert!(own.contains("[convention]") && own.contains(code), "{own}");
770        assert!(own.contains(local), "{own}");
771
772        let linked = recall(&feature);
773        assert!(
774            linked.contains(&format!("{convention} [convention]")),
775            "{linked}"
776        );
777        assert!(!linked.contains(code), "{linked}");
778        assert!(
779            linked.contains("1 code-bound fact(s) withheld: stale"),
780            "{linked}"
781        );
782        assert!(!linked.contains(local), "{linked}");
783
784        std::fs::write(
785            format!("{feature}/retry.rs"),
786            "fn retry() { /* bounded */ }\n",
787        )
788        .unwrap();
789        let same = recall(&feature);
790        assert!(same.contains(&format!("{code} [content]")), "{same}");
791        assert!(!same.contains("withheld"), "{same}");
792    }
793
794    fn declares(action: &str) -> bool {
795        let mut args = Map::new();
796        args.insert("action".to_owned(), Value::String(action.to_owned()));
797        CtxKnowledgeTool.publishes_every_source(Some(&args))
798    }
799
800    /// The recall of the knowledge tool itself, as a declared action
801    /// delivers it.
802    fn recall(root: &str) -> (String, usize) {
803        deliver(root, || {
804            crate::tools::ctx_knowledge::handle(
805                root,
806                "recall",
807                Some("architecture"),
808                None,
809                None,
810                None,
811                "session-1",
812                None,
813                None,
814                None,
815                None,
816                None,
817            )
818        })
819    }
820
821    /// A fact remembered with sources and recalled by a declared action
822    /// gives the reply the lineage of its files. A fact without sources in
823    /// the same reply leaves it unknown. When a source is withheld by a
824    /// tightened rule, or deleted, the lineage refuses and the bound fact is
825    /// no longer recalled — the fact without sources still is.
826    #[test]
827    fn a_declared_recall_carries_the_lineage_of_its_bound_facts() {
828        use lean_ctx::core::archive::delivered::LineageRefusal;
829        let _data = governed();
830        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
831        let (_directory, root) = project();
832        std::fs::write(format!("{root}/auth.rs"), "pub fn verify_rs256() {}\n").expect("source");
833        let value = "Tokens are verified with RS256 in the auth module";
834        remember(&root, "token-check", value);
835        assert!(bind_remembered(
836            &root,
837            Some("architecture"),
838            Some("token-check"),
839            Some(value),
840            &["auth.rs".to_owned()],
841        ));
842        assert!(declares("recall") && declares("timeline") && declares("search"));
843        assert!(!declares("remember") && !declares("status") && !declares("wakeup"));
844
845        let (reply, recorded) = recall(&root);
846        assert!(reply.contains(value), "{reply}");
847        assert_eq!(recorded, 1);
848        assert_eq!(reusable(&root, &reply), Ok(()));
849
850        let typed = "Deployments are promoted by the release captain on Fridays";
851        remember(&root, "release-duty", typed);
852        let (mixed, recorded) = recall(&root);
853        assert!(mixed.contains(value) && mixed.contains(typed), "{mixed}");
854        assert_eq!(recorded, 0, "one fact without a source: unknown");
855        assert_eq!(reusable(&root, &mixed), Err(LineageRefusal::Unknown));
856
857        // The source is reclassified: the recorded reply is refused and the
858        // bound fact is left out of the next recall.
859        std::fs::write(
860            format!("{root}/auth.rs"),
861            "*** TOP SECRET ***\npub fn verify_rs256() {}\n",
862        )
863        .expect("mark");
864        assert_eq!(
865            reusable(&root, &reply),
866            Err(LineageRefusal::SourceNoLongerAdmitted)
867        );
868        let (withheld, recorded) = recall(&root);
869        assert!(!withheld.contains(value), "{withheld}");
870        assert!(withheld.contains(typed), "{withheld}");
871        assert_eq!(recorded, 0);
872
873        std::fs::remove_file(format!("{root}/auth.rs")).expect("delete");
874        assert_eq!(
875            reusable(&root, &reply),
876            Err(LineageRefusal::SourceNoLongerAdmitted)
877        );
878        assert!(!recall(&root).0.contains(value));
879    }
880}
881
882// The jail is the point of these tests; a `no-jail` build switches it off.
883#[cfg(all(test, not(feature = "no-jail")))]
884mod tests {
885    use super::*;
886
887    fn call(ctx: &ToolContext, args: &Value) -> String {
888        CtxKnowledgeTool
889            .handle(args.as_object().unwrap(), ctx)
890            .unwrap()
891            .text
892    }
893
894    #[test]
895    fn okf_export_and_import_paths_stay_in_the_project_jail() {
896        let _data = lean_ctx::core::data_dir::isolated_data_dir();
897        let root = tempfile::tempdir().unwrap();
898        let outside = tempfile::tempdir().unwrap();
899        let ctx = ToolContext {
900            project_root: root.path().to_string_lossy().into_owned(),
901            session: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
902                lean_ctx::core::session::SessionState::new(),
903            ))),
904            ..ToolContext::default()
905        };
906        call(
907            &ctx,
908            &json!({"action": "remember", "category": "architecture",
909                    "key": "parser", "value": "the parser is bounded"}),
910        );
911
912        let export_dir = outside.path().join("okf");
913        let text = call(
914            &ctx,
915            &json!({"action": "export", "format": "okf", "path": export_dir}),
916        );
917        assert!(!export_dir.exists(), "OKF export left the jail: {text}");
918
919        let facts = outside.path().join("facts.json");
920        std::fs::write(
921            &facts,
922            r#"[{"category":"secret","key":"outside","value":"OUTSIDE-JAIL"}]"#,
923        )
924        .unwrap();
925        let text = call(&ctx, &json!({"action": "import", "path": facts}));
926        assert!(
927            !text.contains("Import complete"),
928            "import read outside the jail: {text}"
929        );
930
931        let inside = root.path().join("okf-export");
932        let text = call(
933            &ctx,
934            &json!({"action": "export", "format": "okf", "path": inside}),
935        );
936        assert!(inside.join("index.md").exists(), "{text}");
937        let text = call(&ctx, &json!({"action": "import", "path": inside}));
938        assert!(text.contains("import"), "{text}");
939    }
940
941    /// #270: a fact `ctx_knowledge` remembers is handed to the push on write
942    /// of this process (which pushes the vault within about a second); a
943    /// read that writes nothing is not.
944    #[test]
945    fn a_remembered_fact_asks_for_a_push_and_a_recall_does_not() {
946        use lean_ctx_cloud::sync::on_write::requested;
947        let _data = lean_ctx::core::data_dir::isolated_data_dir();
948        let dir = tempfile::tempdir().unwrap();
949        let root = dir
950            .path()
951            .canonicalize()
952            .unwrap()
953            .to_string_lossy()
954            .into_owned();
955        let ctx = ToolContext {
956            project_root: root.clone(),
957            session: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
958                lean_ctx::core::session::SessionState::new(),
959            ))),
960            ..ToolContext::default()
961        };
962        assert_eq!(requested(&root), 0);
963        call(
964            &ctx,
965            &json!({"action": "remember", "category": "architecture",
966                    "key": "retry", "value": "payments retry three times"}),
967        );
968        assert_eq!(requested(&root), 1, "the write asks for a push");
969        call(&ctx, &json!({"action": "recall", "query": "retry"}));
970        assert_eq!(requested(&root), 1, "a recall writes nothing");
971    }
972}
973
974#[cfg(test)]
975mod session_stats_tests {
976    //! rel12 WP2: `session.stats` `knowledge.written` counts the remembers
977    //! that wrote a fact, never a refused one.
978    use super::*;
979
980    type Session = std::sync::Arc<tokio::sync::RwLock<lean_ctx::core::session::SessionState>>;
981
982    /// The session's persisted `knowledge_written` counter as JSON.
983    fn written(session: &Session) -> Value {
984        serde_json::to_value(&session.blocking_read().stats).unwrap()["knowledge_written"].clone()
985    }
986
987    #[test]
988    fn only_a_successful_remember_counts_as_a_knowledge_write() {
989        let _data = lean_ctx::core::data_dir::isolated_data_dir();
990        let dir = tempfile::tempdir().unwrap();
991        let root = dir
992            .path()
993            .canonicalize()
994            .unwrap()
995            .to_string_lossy()
996            .into_owned();
997        let session: Session = std::sync::Arc::new(tokio::sync::RwLock::new(
998            lean_ctx::core::session::SessionState::new(),
999        ));
1000        let ctx = ToolContext {
1001            project_root: root,
1002            session: Some(session.clone()),
1003            ..ToolContext::default()
1004        };
1005        let run = |args: Value| {
1006            let _ = CtxKnowledgeTool.handle(args.as_object().unwrap(), &ctx);
1007        };
1008
1009        run(json!({"action": "remember", "category": "architecture",
1010                   "key": "retry", "value": "payments retry three times"}));
1011        assert_eq!(written(&session), json!(1), "a stored fact is a write");
1012
1013        run(json!({"action": "remember", "category": "architecture", "key": "retry-cap"}));
1014        assert_eq!(
1015            written(&session),
1016            json!(1),
1017            "a remember without a value is refused and wrote nothing"
1018        );
1019
1020        run(json!({"action": "recall", "query": "retry"}));
1021        assert_eq!(written(&session), json!(1), "a recall is no write");
1022    }
1023
1024    #[test]
1025    fn a_merged_near_duplicate_remember_counts_as_a_knowledge_write() {
1026        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1027        let dir = tempfile::tempdir().unwrap();
1028        let root = dir
1029            .path()
1030            .canonicalize()
1031            .unwrap()
1032            .to_string_lossy()
1033            .into_owned();
1034        let session: Session = std::sync::Arc::new(tokio::sync::RwLock::new(
1035            lean_ctx::core::session::SessionState::new(),
1036        ));
1037        let ctx = ToolContext {
1038            project_root: root,
1039            session: Some(session.clone()),
1040            ..ToolContext::default()
1041        };
1042        let run = |args: Value| {
1043            CtxKnowledgeTool
1044                .handle(args.as_object().unwrap(), &ctx)
1045                .map(|output| output.text)
1046                .unwrap()
1047        };
1048        let value = "use postgres for the primary datastore";
1049
1050        let stored = run(json!({"action": "remember", "category": "architecture",
1051                                "key": "db-primary", "value": value}));
1052        assert!(stored.starts_with("Remembered"), "{stored}");
1053        assert_eq!(written(&session), json!(1), "a stored fact is a write");
1054
1055        // The same statement under another key reinforces the stored fact.
1056        let merged = run(json!({"action": "remember", "category": "architecture",
1057                                "key": "db-store", "value": value}));
1058        assert!(merged.starts_with("Merged"), "{merged}");
1059        assert_eq!(
1060            written(&session),
1061            json!(2),
1062            "a merge into a near-duplicate is a write"
1063        );
1064    }
1065}