1use crate::core::config::Config;
13use serde_json::{Map, Value, json};
14
15const HEAD_LINES: usize = 20;
16const TAIL_LINES: usize = 8;
17const LONG_LINE_HEAD_CHARS: usize = 800;
18const LONG_LINE_TAIL_CHARS: usize = 300;
19const JSON_PREVIEW_KEYS: usize = 32;
20
21pub fn is_firewallable_tool(name: &str) -> bool {
24 matches!(
25 name,
26 "ctx_shell" | "ctx_execute" | "ctx_search" | "ctx_tree"
27 )
28}
29
30pub fn is_protected_read(name: &str) -> bool {
37 name == "ctx_read"
38}
39
40pub(crate) fn min_tokens(config: &Config) -> usize {
42 config.archive.ephemeral_min_tokens_effective()
43}
44
45pub fn should_firewall(tool: &str, output_tokens: usize, config: &Config) -> bool {
47 config.archive.ephemeral_effective()
48 && is_firewallable_tool(tool)
49 && output_tokens >= min_tokens(config)
50}
51
52pub(crate) const DEFAULT_RAW_COMMANDS: &[&str] = &["sqlite3", "psql", "duckdb", "jq"];
58
59pub fn verbatim_cap_exceeded(tool: &str, output_tokens: usize, config: &Config) -> bool {
67 let cap = config.archive.verbatim_max_tokens_effective();
68 cap > 0 && is_firewallable_tool(tool) && output_tokens >= cap
69}
70
71pub fn is_raw_command(command: &str, config: &Config) -> bool {
75 command
76 .split(['|', ';', '&', '\n'])
77 .any(|seg| match seg.split_whitespace().next() {
78 Some(word) => {
81 let prog = word.rsplit('/').next().unwrap_or(word);
82 config.archive.raw_commands.iter().any(|r| r == prog)
83 || (prog == "gh" && (seg.contains("--json") || seg.contains("--jq")))
84 }
85 None => false,
86 })
87}
88
89pub fn should_inline_shell(inline_requested: bool, output_bytes: usize, config: &Config) -> bool {
92 inline_requested && output_bytes <= config.archive.inline_max_bytes_effective()
93}
94
95pub fn summarize(
100 full: &str,
101 archive_id: &str,
102 tool: &str,
103 output_tokens: usize,
104 command: &str,
105) -> String {
106 let chars = full.len();
107 let lines: Vec<&str> = full.lines().collect();
108 let line_count = lines.len();
109
110 let mut out = String::new();
111 out.push_str(&format!(
112 "[Firewalled {tool} output — {chars} chars, {output_tokens} tok, {line_count} lines stored out-of-band]\n"
113 ));
114
115 if let Some(preview) = json_structure_preview(full) {
116 out.push_str("--- JSON structural preview (complete summary; original archived) ---\n");
117 out.push_str(&preview);
118 out.push('\n');
119 } else if line_count > HEAD_LINES + TAIL_LINES + 1 {
120 out.push_str("--- head ---\n");
121 out.push_str(&lines[..HEAD_LINES].join("\n"));
122 out.push_str(&format!(
123 "\n--- … {} lines omitted … ---\n",
124 line_count - HEAD_LINES - TAIL_LINES
125 ));
126 out.push_str("--- tail ---\n");
127 out.push_str(&lines[line_count - TAIL_LINES..].join("\n"));
128 out.push('\n');
129 } else {
130 let head_end = full.floor_char_boundary(LONG_LINE_HEAD_CHARS.min(chars));
132 out.push_str(&full[..head_end]);
133 if chars > LONG_LINE_HEAD_CHARS + LONG_LINE_TAIL_CHARS {
134 out.push_str("\n… (truncated) …\n");
135 let tail_start = full.floor_char_boundary(chars - LONG_LINE_TAIL_CHARS);
136 out.push_str(&full[tail_start..]);
137 out.push('\n');
138 }
139 }
140
141 let max_line = lines.iter().map(|l| l.len()).max().unwrap_or(0);
143 if max_line > 2000 {
144 out.push_str(&format!(
145 "⚠ longest line: {max_line} chars — line-based offset/limit chunking will not help; use ctx_expand(search=…) or ctx_expand(json_keys=true).\n"
146 ));
147 }
148
149 out.push_str("--- guidance ---\n");
158 out.push_str("The full output is archived. Query it, do not re-run the command.\n");
159 if json_structure_preview(full).is_some() {
160 out.push_str(&format!(
161 "Content is JSON: extract what you need, ctx_expand(id=\"{archive_id}\", json_keys=true | json_path=\"…\" | search=\"KEYWORD\"), rather than reading sequentially.\n"
162 ));
163 if command.contains("--json") && !command.contains("--jq") {
164 out.push_str(
165 "Next time, a --jq filter selects only the fields you need at the source.\n",
166 );
167 }
168 } else {
169 out.push_str(&format!(
170 "Slice it: ctx_expand(id=\"{archive_id}\", search=\"KEYWORD\" | head=N | start_line=A, end_line=B). For the next command, narrow at the source (grep -m N, sed -n 'A,Bp', head/tail). Only read the full archive if you genuinely need every line.\n"
171 ));
172 }
173
174 out.push_str("--- retrieve full output ---\n");
175 let path = crate::core::archive::content_path_str(archive_id);
178 if crate::core::protected_store::enforce_protected_store_path(std::path::Path::new(&path))
179 .is_ok()
180 {
181 out.push_str(&format!("Direct: read {path} directly (no MCP)\n"));
182 }
183 out.push_str(&format!("Full: ctx_expand(id=\"{archive_id}\")\n"));
184 out.push_str(&format!(
185 "Range: ctx_expand(id=\"{archive_id}\", start_line=1, end_line=80)\n"
186 ));
187 out.push_str(&format!(
188 "Head: ctx_expand(id=\"{archive_id}\", head=120)\n"
189 ));
190 out.push_str(&format!(
191 "Search: ctx_expand(id=\"{archive_id}\", search=\"ERROR\")\n"
192 ));
193 out.push_str(&format!(
194 "JSON: ctx_expand(id=\"{archive_id}\", json_keys=true)"
195 ));
196 out
197}
198
199pub fn summarize_unavailable(full: &str, tool: &str, output_tokens: usize) -> String {
202 let head_end = full.floor_char_boundary(LONG_LINE_HEAD_CHARS.min(full.len()));
203 let mut out = format!(
204 "[Firewalled {tool} output — {} chars, {output_tokens} tok; recovery unavailable]\n--- preview ---\n{}",
205 full.chars().count(),
206 &full[..head_end],
207 );
208 if full.len() > head_end {
209 out.push_str("\n… (omitted; not archived) …\n");
210 let tail_start = full.ceil_char_boundary(
211 full.len()
212 .saturating_sub(LONG_LINE_TAIL_CHARS)
213 .max(head_end),
214 );
215 out.push_str(&full[tail_start..]);
216 }
217 out.push_str(
218 "\nFull recovery is unavailable. Re-run with a narrower query or output selection.",
219 );
220 out
221}
222
223fn json_structure_preview(full: &str) -> Option<String> {
224 let value: Value = serde_json::from_str(full).ok()?;
225 let root = match value {
226 Value::Object(object) => {
227 let total = object.len();
228 let fields = object
229 .into_iter()
230 .take(JSON_PREVIEW_KEYS)
231 .map(|(key, value)| (key, json_value_shape(&value)))
232 .collect::<Map<_, _>>();
233 json!({
234 "type": "object",
235 "keys": total,
236 "fields": fields,
237 "omitted_keys": total.saturating_sub(JSON_PREVIEW_KEYS),
238 })
239 }
240 other => json_value_shape(&other),
241 };
242 serde_json::to_string(&json!({
243 "preview": "structural",
244 "root": root,
245 }))
246 .ok()
247}
248
249const JSON_STRING_PREVIEW_CHARS: usize = 120;
251const JSON_ARRAY_SAMPLE: usize = 3;
253const JSON_SHAPE_MAX_DEPTH: usize = 2;
255
256fn json_value_shape(value: &Value) -> Value {
257 json_value_shape_depth(value, 0)
258}
259
260fn json_value_shape_depth(value: &Value, depth: usize) -> Value {
261 match value {
262 Value::Null => json!({ "type": "null" }),
263 Value::Bool(b) => json!({ "type": "boolean", "value": b }),
264 Value::Number(n) => json!({ "type": "number", "value": n }),
265 Value::String(text) => {
266 let char_count = text.chars().count();
267 if char_count <= JSON_STRING_PREVIEW_CHARS {
268 json!({ "type": "string", "value": text })
269 } else {
270 let preview: String = text.chars().take(JSON_STRING_PREVIEW_CHARS).collect();
271 json!({
272 "type": "string",
273 "chars": char_count,
274 "preview": format!("{preview}…"),
275 })
276 }
277 }
278 Value::Array(items) => {
279 if depth >= JSON_SHAPE_MAX_DEPTH {
280 return json!({ "type": "array", "items": items.len() });
281 }
282 let sample: Vec<Value> = items
283 .iter()
284 .take(JSON_ARRAY_SAMPLE)
285 .map(|v| json_value_shape_depth(v, depth + 1))
286 .collect();
287 json!({
288 "type": "array",
289 "items": items.len(),
290 "sample": sample,
291 })
292 }
293 Value::Object(fields) => {
294 if depth >= JSON_SHAPE_MAX_DEPTH {
295 return json!({ "type": "object", "keys": fields.len() });
296 }
297 let preview: Map<String, Value> = fields
298 .iter()
299 .take(8)
300 .map(|(k, v)| (k.clone(), json_value_shape_depth(v, depth + 1)))
301 .collect();
302 json!({
303 "type": "object",
304 "keys": fields.len(),
305 "fields": preview,
306 })
307 }
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
318 fn guidance_queries_the_archive_and_never_asks_for_a_re_run() {
319 let skill = include_str!("../templates/SKILL.md");
320 assert!(skill.contains("Do not re-run the command"), "{skill}");
321 let prose = (0..400).fold(String::new(), |mut s, i| {
322 s.push_str(&format!("src/x.rs:{i}: match line {i}\n"));
323 s
324 });
325 let json = format!(
326 "[{}]",
327 (0..200)
328 .map(|i| format!("{{\"n\":{i},\"t\":\"title {i}\"}}"))
329 .collect::<Vec<_>>()
330 .join(",")
331 );
332 for (full, command) in [
333 (prose.as_str(), "grep -rn match src"),
334 (json.as_str(), "gh issue list --json number,title"),
335 ] {
336 let digest = summarize(full, "abc123", "ctx_shell", 5000, command);
337 let guidance = digest
338 .split("--- guidance ---\n")
339 .nth(1)
340 .and_then(|rest| rest.split("--- retrieve full output ---").next())
341 .expect("guidance block");
342 assert!(
343 guidance.starts_with(
344 "The full output is archived. Query it, do not re-run the command.\n"
345 ),
346 "{guidance}"
347 );
348 assert!(guidance.contains("ctx_expand(id=\"abc123\""), "{guidance}");
349 let lower = guidance.to_lowercase();
350 assert!(!lower.contains("re-run the command with"), "{guidance}");
351 assert!(
352 !lower.contains("narrow the command at the source"),
353 "{guidance}"
354 );
355 assert_eq!(
356 digest,
357 summarize(full, "abc123", "ctx_shell", 5000, command)
358 );
359 }
360 }
361
362 #[test]
363 fn firewallable_tools_are_outputs_not_reads() {
364 assert!(is_firewallable_tool("ctx_shell"));
365 assert!(is_firewallable_tool("ctx_search"));
366 assert!(is_firewallable_tool("ctx_tree"));
367 assert!(is_firewallable_tool("ctx_execute"));
368 assert!(!is_firewallable_tool("ctx_read"));
369 assert!(!is_firewallable_tool("ctx_knowledge"));
370 }
371
372 #[test]
373 fn protected_reads_are_file_readers_and_never_firewallable() {
374 assert!(is_protected_read("ctx_read"));
377 assert!(!is_firewallable_tool("ctx_read"));
378 assert!(!is_protected_read("ctx_shell"));
379 assert!(!is_protected_read("ctx_search"));
380 }
381
382 #[test]
383 fn should_firewall_respects_tool_and_threshold() {
384 let _env_lock = crate::core::data_dir::test_env_lock();
385 let mut cfg = Config::default();
386 cfg.archive.enabled = true;
387 cfg.archive.ephemeral = true;
388 cfg.archive.ephemeral_min_tokens = 2000;
389 crate::test_env::remove_var("LEAN_CTX_EPHEMERAL");
391 crate::test_env::remove_var("LEAN_CTX_EPHEMERAL_MIN_TOKENS");
392
393 assert!(should_firewall("ctx_shell", 5000, &cfg));
394 assert!(!should_firewall("ctx_shell", 1000, &cfg)); assert!(!should_firewall("ctx_read", 5000, &cfg)); }
397
398 #[test]
399 fn dataset_commands_bypass_the_firewall_but_prose_does_not() {
400 let cfg = Config::default();
401 assert!(is_raw_command(
402 "sqlite3 -header backup.db \"select 1\"",
403 &cfg
404 ));
405 assert!(is_raw_command("/usr/bin/psql -c 'select 1'", &cfg));
406 assert!(is_raw_command("cat x.json | jq '.[]'", &cfg));
407 assert!(is_raw_command("gh issue list --json number,title", &cfg));
408 assert!(!is_raw_command("gh issue view 1260", &cfg));
410 assert!(!is_raw_command("grep -rn sqlite3 src/", &cfg));
411 assert!(!is_raw_command("cargo test", &cfg));
412
413 let mut off = Config::default();
415 off.archive.raw_commands.clear();
416 assert!(!is_raw_command("sqlite3 backup.db 'select 1'", &off));
417 }
418
419 #[test]
420 fn verbatim_cap_fires_only_above_threshold_and_only_for_firewallable_tools() {
421 let _env_lock = crate::core::data_dir::test_env_lock();
422 crate::test_env::remove_var("LEAN_CTX_VERBATIM_MAX_TOKENS");
423 let mut cfg = Config::default();
424 cfg.archive.verbatim_max_tokens = 10_000;
425 assert!(verbatim_cap_exceeded("ctx_shell", 10_000, &cfg));
426 assert!(!verbatim_cap_exceeded("ctx_shell", 9_999, &cfg));
427 assert!(!verbatim_cap_exceeded("ctx_read", 50_000, &cfg));
428
429 cfg.archive.verbatim_max_tokens = 0;
431 assert!(!verbatim_cap_exceeded("ctx_shell", 1_000_000, &cfg));
432 }
433
434 #[test]
435 fn inline_shell_stays_inline_under_byte_cap() {
436 let _env_lock = crate::core::data_dir::test_env_lock();
437 let mut cfg = Config::default();
438 cfg.archive.inline_max_bytes = 1024;
439 crate::test_env::remove_var("LEAN_CTX_INLINE_MAX_BYTES");
440
441 assert!(should_inline_shell(true, 1024, &cfg));
442 assert!(should_inline_shell(true, 0, &cfg));
443 }
444
445 #[test]
446 fn inline_shell_over_byte_cap_uses_archive_path() {
447 let _env_lock = crate::core::data_dir::test_env_lock();
449 let mut cfg = Config::default();
450 cfg.archive.inline_max_bytes = 1024;
451 crate::test_env::remove_var("LEAN_CTX_INLINE_MAX_BYTES");
452
453 assert!(!should_inline_shell(true, 1025, &cfg));
454 }
455
456 #[test]
457 fn inline_shell_requires_explicit_request_and_honors_env_cap() {
458 let _env_lock = crate::core::data_dir::test_env_lock();
461 let mut cfg = Config::default();
462 cfg.archive.inline_max_bytes = 1024;
463 crate::test_env::set_var("LEAN_CTX_INLINE_MAX_BYTES", "2048");
464
465 assert!(!should_inline_shell(false, 1, &cfg));
466 assert!(should_inline_shell(true, 2048, &cfg));
467 assert!(!should_inline_shell(true, 2049, &cfg));
468
469 crate::test_env::remove_var("LEAN_CTX_INLINE_MAX_BYTES");
470 }
471
472 #[test]
473 fn summarize_includes_excerpt_stats_and_ref() {
474 let full = (1..=200)
475 .map(|i| format!("line {i}"))
476 .collect::<Vec<_>>()
477 .join("\n");
478 let digest = summarize(&full, "abc123", "ctx_shell", 1234, "cargo test");
479 assert!(digest.contains("Firewalled ctx_shell output"));
480 assert!(digest.contains("1234 tok"));
481 assert!(digest.contains("line 1")); assert!(digest.contains("line 200")); assert!(digest.contains("lines omitted"));
484 assert!(digest.contains("ctx_expand(id=\"abc123\")"));
485 assert!(digest.contains("json_keys=true"));
486 assert!(digest.len() < full.len());
488 }
489
490 #[test]
491 fn summarize_handles_single_giant_line() {
492 let full = "x".repeat(5000);
493 let digest = summarize(&full, "id9", "ctx_search", 1300, "rg pattern");
494 assert!(digest.contains("Firewalled ctx_search output"));
495 assert!(digest.contains("truncated"));
496 assert!(digest.len() < full.len());
497 }
498
499 #[test]
500 fn summarize_json_uses_complete_structural_document() {
501 let full = serde_json::to_string(&json!({
502 "body": "x".repeat(5000),
503 "files": [{"path": "src/a.rs"}, {"path": "src/b.rs"}],
504 "state": "MERGED",
505 }))
506 .unwrap();
507
508 let digest = summarize(
509 &full,
510 "json1",
511 "ctx_shell",
512 2000,
513 "gh issue view --json comments",
514 );
515 assert!(!digest.contains("… (truncated) …"));
516 let preview = digest
517 .lines()
518 .find(|line| line.starts_with("{\"preview\":"))
519 .expect("structural preview JSON");
520 let parsed: Value = serde_json::from_str(preview).expect("preview remains valid JSON");
521 assert_eq!(parsed["root"]["fields"]["body"]["chars"], 5000);
523 assert!(
524 parsed["root"]["fields"]["body"]["preview"]
525 .as_str()
526 .unwrap()
527 .starts_with("xxx")
528 );
529 assert_eq!(parsed["root"]["fields"]["state"]["value"], "MERGED");
531 assert_eq!(parsed["root"]["fields"]["files"]["items"], 2);
533 assert!(parsed["root"]["fields"]["files"]["sample"].is_array());
534 assert_eq!(parsed["root"]["keys"], 3);
535 assert!(digest.contains("original archived"));
536 assert!(digest.contains("ctx_expand(id=\"json1\", json_keys=true)"));
537 }
538
539 #[test]
540 fn json_structure_preview_caps_fields_at_valid_boundary() {
541 let object = (0..40)
542 .map(|index| (format!("key_{index:02}"), json!(index)))
543 .collect::<Map<_, _>>();
544 let full = serde_json::to_string(&object).unwrap();
545 let preview = json_structure_preview(&full).unwrap();
546 let parsed: Value = serde_json::from_str(&preview).unwrap();
547
548 assert_eq!(parsed["root"]["fields"].as_object().unwrap().len(), 32);
549 assert_eq!(parsed["root"]["omitted_keys"], 8);
550 let first_field = &parsed["root"]["fields"]["key_00"];
552 assert_eq!(first_field["type"], "number");
553 assert_eq!(first_field["value"], 0);
554 }
555
556 #[test]
557 fn json_value_shape_includes_previews_with_depth_limit() {
558 let nested = json!({
559 "name": "hello world",
560 "count": 42,
561 "active": true,
562 "tags": ["rust", "mcp", "context"],
563 "meta": {
564 "deep": {
565 "very_deep": "should not recurse here"
566 }
567 }
568 });
569 let shape = json_value_shape(&nested);
570 assert_eq!(shape["type"], "object");
572 assert!(shape["fields"].is_object());
573 assert_eq!(shape["fields"]["name"]["value"], "hello world");
575 assert_eq!(shape["fields"]["count"]["value"], 42);
577 assert_eq!(shape["fields"]["active"]["value"], true);
579 assert_eq!(shape["fields"]["tags"]["items"], 3);
581 assert_eq!(shape["fields"]["tags"]["sample"][0]["value"], "rust");
582 let deep = &shape["fields"]["meta"]["fields"]["deep"];
584 assert_eq!(deep["type"], "object");
585 assert_eq!(deep["keys"], 1);
586 assert!(deep.get("fields").is_none());
587 }
588
589 #[test]
590 fn json_value_shape_truncates_long_strings() {
591 let long_str = "a".repeat(500);
592 let val = json!(long_str);
593 let shape = json_value_shape(&val);
594 assert_eq!(shape["type"], "string");
595 assert_eq!(shape["chars"], 500);
596 let preview = shape["preview"].as_str().unwrap();
597 assert!(preview.ends_with('…'));
598 assert!(preview.len() <= JSON_STRING_PREVIEW_CHARS + 4); }
600}