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