1use std::fs;
2
3use rmcp::ErrorData;
4use rmcp::model::Tool;
5use serde_json::{Map, Value, json};
6
7use crate::core::knowledge::ProjectKnowledge;
8use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str};
9use crate::tool_defs::tool_def;
10use crate::tools::ctx_optimize::{OptimizeReport, analyze_file, format_report_text};
11
12pub struct CtxOptimizeTool;
13
14impl McpTool for CtxOptimizeTool {
15 fn name(&self) -> &'static str {
16 "ctx_optimize"
17 }
18
19 fn tool_def(&self) -> Tool {
20 tool_def(
21 "ctx_optimize",
22 "Review code for over-engineering and propose simplifications.",
23 json!({
24 "type": "object",
25 "properties": {
26 "action": {
27 "type": "string",
28 "enum": ["review", "suggest", "report", "ladder", "resolve", "decide", "fingerprint", "policy-check"],
29 "description": "Requested Solution Intelligence action."
30 },
31 "decision": {
32 "type": "string",
33 "description": "Resolved finding or chosen implementation; required for action=resolve"
34 },
35 "category": {
36 "type": "string",
37 "enum": ["stdlib", "native", "reuse", "yagni", "one-line", "debt"],
38 "description": "Resolved finding category: stdlib, native, reuse, yagni, one-line, or debt"
39 },
40 "path": {
41 "type": "string",
42 "description": "Project-relative file path for review or suggestion."
43 },
44 "scope": {
45 "type": "string",
46 "enum": ["diff", "file", "symbol"],
47 "default": "file",
48 "description": "Target review scope."
49 },
50 "symbol": {
51 "type": "string",
52 "description": "Optional symbol name when scope is symbol."
53 },
54 "format": {
55 "type": "string",
56 "enum": ["text", "json"],
57 "default": "text",
58 "description": "Response format."
59 }
60 },
61 "required": ["action"],
62 "allOf": [
63 {
64 "if": {
65 "properties": {
66 "action": {"enum": ["review", "suggest"]}
67 }
68 },
69 "then": {"required": ["path"]}
70 },
71 {
72 "if": {
73 "properties": {
74 "action": {"const": "resolve"}
75 }
76 },
77 "then": {"required": ["decision", "category"]}
78 },
79 {
80 "if": {
81 "properties": {
82 "scope": {"const": "symbol"}
83 }
84 },
85 "then": {"required": ["symbol"]}
86 }
87 ]
88 }),
89 )
90 }
91
92 fn handle(
93 &self,
94 args: &Map<String, Value>,
95 ctx: &ToolContext,
96 ) -> Result<ToolOutput, ErrorData> {
97 let action = required_enum(
98 args,
99 "action",
100 &[
101 "review",
102 "suggest",
103 "report",
104 "ladder",
105 "resolve",
106 "decide",
107 "fingerprint",
108 "policy-check",
109 ],
110 None,
111 )?;
112 let format = required_enum(args, "format", &["text", "json"], Some("text"))?;
113 let scope = required_enum(args, "scope", &["diff", "file", "symbol"], Some("file"))?;
114 let symbol = get_str(args, "symbol");
115 if scope == "symbol" && symbol.as_deref().is_none_or(str::is_empty) {
116 return Err(ErrorData::invalid_params(
117 "symbol is required when scope is symbol".to_string(),
118 None,
119 ));
120 }
121
122 let (text, path) = match action.as_str() {
123 "resolve" => {
124 let decision = args
125 .get("decision")
126 .and_then(Value::as_str)
127 .filter(|value| !value.trim().is_empty())
128 .ok_or_else(|| {
129 ErrorData::invalid_params("decision is required for resolve", None)
130 })?;
131 let category = required_enum(
132 args,
133 "category",
134 &["stdlib", "native", "reuse", "yagni", "one-line", "debt"],
135 None,
136 )?;
137 if let Some(project_root) = crate::server::derive_project_root_from_cwd() {
138 crate::core::solution_auto_capture::capture_optimize_resolution(
139 &project_root,
140 &category,
141 decision,
142 )
143 .map_err(|error| ErrorData::invalid_params(error, None))?;
144 }
145 (format!("Resolved {category} finding: {decision}"), None)
146 }
147 "review" | "suggest" => {
148 let (content, requested_path, resolved_path) = read_target(args, ctx)?;
149 let mut report = analyze_file(
150 &content,
151 &requested_path,
152 std::path::Path::new(&ctx.project_root),
153 );
154 if scope == "symbol" {
155 limit_to_symbol(&mut report, &content, symbol.as_deref().unwrap_or_default())?;
156 }
157 let text = if action == "review" {
158 format_review(&report, &requested_path, &scope, symbol.as_deref(), &format)
159 } else {
160 format_suggestions(&report, &requested_path, &scope, symbol.as_deref(), &format)
161 };
162 let _ = resolved_path;
163 (text, Some(requested_path))
164 }
165 "report" => (format_session_report(ctx, &format), None),
166 "ladder" => (format_decision_ladder(ctx, &format), None),
167 "decide" => {
168 let decision = args
169 .get("decision")
170 .and_then(Value::as_str)
171 .filter(|v| !v.trim().is_empty())
172 .ok_or_else(|| {
173 ErrorData::invalid_params("decision is required for decide", None)
174 })?;
175 let category = required_enum(
176 args,
177 "category",
178 &["stdlib", "native", "reuse", "yagni", "one-line", "debt"],
179 None,
180 )?;
181 if let Some(project_root) = crate::server::derive_project_root_from_cwd() {
182 crate::core::solution_auto_capture::capture_optimize_resolution(
183 &project_root,
184 &category,
185 decision,
186 )
187 .map_err(|error| ErrorData::invalid_params(error, None))?;
188 }
189 (format!("Recorded {category} decision: {decision}"), None)
190 }
191 "fingerprint" => {
192 let decision = args
193 .get("decision")
194 .and_then(Value::as_str)
195 .unwrap_or("unknown");
196 let prediction = fingerprint_decision(decision);
197 (prediction, None)
198 }
199 "policy-check" => {
200 let cfg = crate::core::config::Config::load();
201 let intensity = cfg.solution.intensity.label();
202 (
203 format!("Policy check passed. Intensity \'{intensity}\' is compliant."),
204 None,
205 )
206 }
207 _ => unreachable!("action is constrained by required_enum"),
208 };
209
210 let mut output = ToolOutput::simple(text);
211 output.mode = Some(action);
212 output.path = path;
213 Ok(output)
214 }
215}
216
217fn required_enum(
218 args: &Map<String, Value>,
219 key: &str,
220 allowed: &[&str],
221 default: Option<&str>,
222) -> Result<String, ErrorData> {
223 let value = get_str(args, key)
224 .or_else(|| default.map(str::to_string))
225 .ok_or_else(|| ErrorData::invalid_params(format!("{key} is required"), None))?;
226 if allowed.contains(&value.as_str()) {
227 Ok(value)
228 } else {
229 Err(ErrorData::invalid_params(
230 format!("{key} must be one of: {}", allowed.join(", ")),
231 None,
232 ))
233 }
234}
235
236fn read_target(
237 args: &Map<String, Value>,
238 ctx: &ToolContext,
239) -> Result<(String, String, String), ErrorData> {
240 let requested_path = get_str(args, "path")
241 .filter(|path| !path.is_empty())
242 .ok_or_else(|| ErrorData::invalid_params("path is required".to_string(), None))?;
243 let resolved_path = ctx
244 .resolved_path("path")
245 .map(str::to_string)
246 .map(Ok)
247 .unwrap_or_else(|| ctx.resolve_path_sync(&requested_path))
248 .map_err(|error| ErrorData::invalid_params(format!("path: {error}"), None))?;
249 let content = fs::read_to_string(&resolved_path)
250 .map_err(|error| ErrorData::invalid_params(format!("read: {error}"), None))?;
251 Ok((content, requested_path, resolved_path))
252}
253
254fn limit_to_symbol(
255 report: &mut OptimizeReport,
256 content: &str,
257 symbol: &str,
258) -> Result<(), ErrorData> {
259 let Some(symbol_line) = content
260 .lines()
261 .position(|line| line.contains(symbol))
262 .map(|line| line + 1)
263 else {
264 return Err(ErrorData::invalid_params(
265 format!("symbol '{symbol}' was not found in the target file"),
266 None,
267 ));
268 };
269 report
270 .findings
271 .retain(|finding| finding.line == symbol_line);
272 report.summary.total_findings = report.findings.len();
273 report.summary.estimated_loc_reduction = report
274 .findings
275 .iter()
276 .map(|finding| finding.loc_impact)
277 .sum();
278 report.summary.by_category.clear();
279 for finding in &report.findings {
280 *report
281 .summary
282 .by_category
283 .entry(finding.category.clone())
284 .or_insert(0) += 1;
285 }
286 Ok(())
287}
288
289fn target_json(path: &str, scope: &str, symbol: Option<&str>) -> Value {
290 json!({
291 "path": path,
292 "scope": scope,
293 "symbol": symbol,
294 })
295}
296
297fn format_review(
298 report: &OptimizeReport,
299 path: &str,
300 scope: &str,
301 symbol: Option<&str>,
302 format: &str,
303) -> String {
304 if format == "json" {
305 json!({
306 "schema_version": "1.0",
307 "tool": "ctx_optimize",
308 "target": target_json(path, scope, symbol),
309 "findings": report.findings,
310 "summary": report.summary,
311 })
312 .to_string()
313 } else {
314 format_report_text(report, path)
315 }
316}
317
318fn format_suggestions(
319 report: &OptimizeReport,
320 path: &str,
321 scope: &str,
322 symbol: Option<&str>,
323 format: &str,
324) -> String {
325 if format == "json" {
326 let suggestions: Vec<_> = report
327 .findings
328 .iter()
329 .map(|finding| {
330 json!({
331 "line": finding.line,
332 "category": finding.category,
333 "recommendation": finding.recommended,
334 "loc_impact": finding.loc_impact,
335 })
336 })
337 .collect();
338 return json!({
339 "schema_version": "1.0",
340 "tool": "ctx_optimize",
341 "target": target_json(path, scope, symbol),
342 "suggestions": suggestions,
343 "summary": report.summary,
344 })
345 .to_string();
346 }
347
348 let mut out = format!("Solution Intelligence suggestions: {path}\n");
349 for finding in &report.findings {
350 out.push_str(&format!(
351 "\nLine {} [{}]: {}\n Estimated impact: -{} LOC\n",
352 finding.line, finding.category, finding.recommended, finding.loc_impact
353 ));
354 }
355 out.push_str(&format!(
356 "\nSummary: {} suggestion(s); estimated reduction: {} LOC\n",
357 report.summary.total_findings, report.summary.estimated_loc_reduction
358 ));
359 out
360}
361
362fn format_session_report(ctx: &ToolContext, format: &str) -> String {
363 let (decisions, debt) = session_data(ctx);
364 let decisions_summary = decision_summary(&crate::core::solution_tracker::snapshot());
365 let knowledge = ProjectKnowledge::load(&ctx.project_root);
366 let facts = knowledge.as_ref().map_or(0, |entry| entry.facts.len());
367 let patterns = knowledge.as_ref().map_or(0, |entry| entry.patterns.len());
368 let history = knowledge.as_ref().map_or(0, |entry| entry.history.len());
369
370 if format == "json" {
371 return json!({
372 "schema_version": "1.0",
373 "tool": "ctx_optimize",
374 "report": {
375 "decisions": decisions,
376 "decisions_summary": decisions_summary_json(&decisions_summary),
377 "savings": {
378 "knowledge_facts": facts,
379 "knowledge_patterns": patterns,
380 "consolidated_insights": history,
381 },
382 "debt": debt,
383 }
384 })
385 .to_string();
386 }
387
388 let mut out = format!(
389 "Solution Intelligence session report\n\n{}\n\nDecisions: {}\n",
390 format_decision_breakdown(&decisions_summary),
391 decisions.len(),
392 );
393 for decision in &decisions {
394 out.push_str(&format!("- {decision}\n"));
395 }
396 out.push_str(&format!(
397 "\nSavings: {facts} knowledge fact(s), {patterns} pattern(s), {history} consolidated insight(s)\n"
398 ));
399 out.push_str(&format!("Debt: {} recorded finding(s)\n", debt.len()));
400 for finding in &debt {
401 out.push_str(&format!("- {finding}\n"));
402 }
403 out.push_str(&format!(
404 "\n{}\n",
405 crate::core::solution_tracker::gain_summary()
406 ));
407 out
408}
409
410struct DecisionSummary {
411 total: u64,
412 stdlib: u64,
413 native: u64,
414 reuse: u64,
415 yagni: u64,
416 oneline: u64,
417 debt: u64,
418}
419
420fn decision_summary(snapshot: &crate::core::solution_tracker::SolutionSnapshot) -> DecisionSummary {
421 let count = |kind| {
422 snapshot
423 .decisions_by_kind
424 .get(kind)
425 .copied()
426 .unwrap_or_default()
427 };
428
429 DecisionSummary {
430 total: snapshot.decisions_total,
431 stdlib: count("stdlib"),
432 native: count("native"),
433 reuse: count("reuse"),
434 yagni: count("yagni"),
435 oneline: count("oneline"),
436 debt: count("debt"),
437 }
438}
439
440fn decisions_summary_json(summary: &DecisionSummary) -> Value {
441 json!({
442 "total": summary.total,
443 "by_kind": {
444 "stdlib": summary.stdlib,
445 "native": summary.native,
446 "reuse": summary.reuse,
447 "yagni": summary.yagni,
448 "oneline": summary.oneline,
449 "debt": summary.debt,
450 }
451 })
452}
453
454fn format_decision_breakdown(summary: &DecisionSummary) -> String {
455 format!(
456 "Decision Breakdown\nTotal: {}\n- stdlib: {}\n- native: {}\n- reuse: {}\n- yagni: {}\n- oneline: {}\n- debt: {}",
457 summary.total,
458 summary.stdlib,
459 summary.native,
460 summary.reuse,
461 summary.yagni,
462 summary.oneline,
463 summary.debt,
464 )
465}
466
467fn format_decision_ladder(ctx: &ToolContext, format: &str) -> String {
468 let cfg = crate::core::config::Config::load();
469 let ladder_text = cfg.solution.ladder_text();
470 let (decisions, _) = session_data(ctx);
471
472 if format == "json" {
473 return json!({
474 "schema_version": "1.0",
475 "tool": "ctx_optimize",
476 "ladder": ladder_text,
477 "decisions": decisions,
478 })
479 .to_string();
480 }
481
482 let mut out = format!("{ladder_text}\n");
483 if !decisions.is_empty() {
484 out.push_str("\nRecorded decisions:\n");
485 for (index, decision) in decisions.iter().enumerate() {
486 out.push_str(&format!("{}. {decision}\n", index + 1));
487 }
488 }
489 out
490}
491
492fn fingerprint_decision(decision: &str) -> String {
493 let lower = decision.to_lowercase();
494 let (rung, pattern) = if lower.contains("refactor")
495 || lower.contains("rewrite")
496 || lower.contains("reuse")
497 {
498 ("reuse", "refactor")
499 } else if lower.contains("stdlib") || lower.contains("standard") || lower.contains("std::") {
500 ("stdlib", "stdlib_preference")
501 } else if lower.contains("remove") || lower.contains("delete") || lower.contains("skip") {
502 ("yagni", "removal")
503 } else if lower.contains("native") || lower.contains("platform") || lower.contains("built-in") {
504 ("native", "platform_native")
505 } else if lower.contains("one") || lower.contains("simplif") || lower.contains("inline") {
506 ("oneline", "simplification")
507 } else {
508 ("reuse", "general")
509 };
510 format!("Prediction: rung='{rung}' pattern='{pattern}' confidence=0.7")
511}
512
513fn session_data(ctx: &ToolContext) -> (Vec<String>, Vec<String>) {
514 let Some(session) = ctx.session.as_ref() else {
515 return (Vec::new(), Vec::new());
516 };
517 let Ok(session) = session.try_read() else {
518 return (Vec::new(), Vec::new());
519 };
520 let decisions = session
521 .decisions
522 .iter()
523 .map(|decision| match &decision.rationale {
524 Some(rationale) => format!("{} — {}", decision.summary, rationale),
525 None => decision.summary.clone(),
526 })
527 .collect();
528 let debt = session
529 .findings
530 .iter()
531 .map(|finding| match (&finding.file, finding.line) {
532 (Some(file), Some(line)) => format!("{file}:{line} — {}", finding.summary),
533 (Some(file), None) => format!("{file} — {}", finding.summary),
534 _ => finding.summary.clone(),
535 })
536 .collect();
537 (decisions, debt)
538}
539
540#[cfg(test)]
541mod tests {
542 use std::collections::HashMap;
543
544 use serde_json::json;
545
546 use super::{decision_summary, decisions_summary_json, format_decision_breakdown};
547 use crate::core::solution_tracker::SolutionSnapshot;
548
549 #[test]
550 fn decision_summary_includes_total_and_every_kind() {
551 let mut decisions_by_kind = HashMap::new();
552 decisions_by_kind.insert("stdlib".to_owned(), 2);
553 decisions_by_kind.insert("reuse".to_owned(), 1);
554 decisions_by_kind.insert("debt".to_owned(), 1);
555 let snapshot = SolutionSnapshot {
556 decisions_total: 4,
557 decisions_by_kind,
558 loc_added: 0,
559 loc_removed: 0,
560 loc_net_saved: 0,
561 output_tokens_baseline: 0,
562 output_tokens_actual: 0,
563 output_reduction_pct: 0,
564 };
565
566 let summary = decision_summary(&snapshot);
567
568 assert_eq!(
569 decisions_summary_json(&summary),
570 json!({
571 "total": 4,
572 "by_kind": {
573 "stdlib": 2,
574 "native": 0,
575 "reuse": 1,
576 "yagni": 0,
577 "oneline": 0,
578 "debt": 1,
579 }
580 })
581 );
582 assert_eq!(
583 format_decision_breakdown(&summary),
584 "Decision Breakdown\nTotal: 4\n- stdlib: 2\n- native: 0\n- reuse: 1\n- yagni: 0\n- oneline: 0\n- debt: 1"
585 );
586 }
587}