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