aicx 0.6.0

Operator CLI + MCP server: canonical corpus first, optional semantic index second (Claude Code, Codex, Gemini)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! MCP (Model Context Protocol) server for aicx.
//!
//! Exposes aicx functionality as MCP tools so agents can search canonical
//! chunks, rank artifacts, and retrieve steer metadata.
//!
//! Supports stdio and streamable HTTP transports.
//!
//! Vibecrafted with AI Agents by VetCoders (c)2026 VetCoders

use clap::ValueEnum;
use rmcp::schemars::{self, JsonSchema};
use rmcp::{
    ErrorData as McpError, handler::server::tool::ToolRouter, handler::server::wrapper::Parameters,
    model::*, tool, tool_router,
};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};

/// Guard that prevents concurrent background refresh child-process spawns.
static RESCAN_RUNNING: AtomicBool = AtomicBool::new(false);

use crate::rank;
use crate::store;
use crate::types::FrameKind;

// ============================================================================
// Tool parameter & result types
// ============================================================================

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum McpTransport {
    Stdio,
    #[value(alias = "sse")]
    Http,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SearchParams {
    /// Search query text
    pub query: String,
    /// Max results to return (default: 10)
    #[serde(default = "default_limit")]
    pub limit: usize,
    /// Optional project filter (case-insensitive substring)
    pub project: Option<String>,
    /// Minimum score threshold (0-100)
    pub score: Option<u8>,
    /// Hours to look back (0 = all time)
    pub hours: Option<u64>,
    /// Optional agent filter
    pub agent: Option<String>,
    /// Optional date filter (single day or range)
    pub date: Option<String>,
    /// Optional lower date bound or single-day shorthand
    pub since: Option<String>,
    /// Optional upper date bound
    pub until: Option<String>,
    /// Optional sort order: newest, oldest, score
    pub sort: Option<String>,
    /// Optional frame/channel filter: user_msg, agent_reply, internal_thought, tool_call
    pub frame_kind: Option<FrameKind>,
}

fn default_limit() -> usize {
    10
}

const MAX_SCORE_FILTER: u8 = 100;

#[derive(Debug, Deserialize, JsonSchema)]
pub struct RankParams {
    /// Project name (required)
    pub project: String,
    /// Hours to look back (default: 72)
    #[serde(default = "default_rank_hours")]
    pub hours: u64,
    /// Only show chunks scoring >= 5
    #[serde(default)]
    pub strict: bool,
    /// Optional agent filter
    pub agent: Option<String>,
    /// Optional lower date bound or single-day shorthand
    pub since: Option<String>,
    /// Optional upper date bound
    pub until: Option<String>,
    /// Optional sort order: newest, oldest, score
    pub sort: Option<String>,
    /// Show only top N bundles
    pub top: Option<usize>,
}

fn default_rank_hours() -> u64 {
    72
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SteerParams {
    /// Filter by run_id (exact match against sidecar metadata)
    pub run_id: Option<String>,
    /// Filter by prompt_id (exact match against sidecar metadata)
    pub prompt_id: Option<String>,
    /// Filter by agent name: claude, codex, gemini (case-insensitive)
    pub agent: Option<String>,
    /// Filter by kind: conversations, plans, reports, other
    pub kind: Option<String>,
    /// Filter by frame/channel: user_msg, agent_reply, internal_thought, tool_call
    pub frame_kind: Option<FrameKind>,
    /// Filter by project (case-insensitive substring)
    pub project: Option<String>,
    /// Filter by date (YYYY-MM-DD, or range like 2026-03-20..2026-03-28)
    pub date: Option<String>,
    /// Max results (default: 20)
    #[serde(default = "default_steer_limit")]
    pub limit: usize,
    /// Minimum score threshold (0-100)
    pub score: Option<u8>,
    /// Sort order (newest, oldest, score)
    pub sort: Option<String>,
    /// Date boundary
    pub since: Option<String>,
    /// Date boundary
    pub until: Option<String>,
}

fn default_steer_limit() -> usize {
    20
}

#[derive(Debug, Serialize)]
struct RankResponse {
    project: String,
    hours: u64,
    strict: bool,
    results: usize,
    items: Vec<RankItem>,
}

#[derive(Debug, Serialize)]
struct RankItem {
    file: String,
    project: String,
    date: String,
    timestamp: Option<String>,
    kind: String,
    agent: String,
    score: u8,
    label: String,
    signal: usize,
    noise: usize,
    total: usize,
    density: String,
}

#[derive(Debug, Serialize)]
struct SteerResponse {
    results: usize,
    items: Vec<serde_json::Value>,
}

fn incremental_rescan_args(hours: u64, project: Option<&str>) -> Vec<String> {
    let mut args = vec![
        "all".to_string(),
        "-H".to_string(),
        hours.to_string(),
        "--incremental".to_string(),
        "--emit".to_string(),
        "none".to_string(),
    ];

    if let Some(project) = project {
        args.push("-p".to_string());
        args.push(project.to_string());
    }

    args
}

// ============================================================================
// MCP Server
// ============================================================================

#[derive(Clone)]
pub struct AicxMcpServer {
    tool_router: ToolRouter<Self>,
}

impl Default for AicxMcpServer {
    fn default() -> Self {
        Self::new()
    }
}

#[tool_router]
impl AicxMcpServer {
    pub fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
        }
    }

    #[tool(
        name = "aicx_search",
        description = "Search stored AI session chunks. Uses memex semantic retrieval when available and otherwise falls back to canonical-store fuzzy search. Returns quality-scored results with matched lines."
    )]
    async fn search(
        &self,
        Parameters(params): Parameters<SearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let query = params.query;
        let limit = params.limit.min(50);
        let project = params.project;
        let score = validate_score_filter(params.score)?;
        let hours = params.hours.unwrap_or(0);
        let date = params.date;
        let frame_kind = params.frame_kind;
        let fetch_limit = if score.is_some() || date.is_some() || hours > 0 {
            limit.saturating_mul(5).max(50)
        } else {
            limit
        };

        // Non-blocking auto-rescan with rate-limit guard.
        if !RESCAN_RUNNING.swap(true, Ordering::SeqCst) {
            let args = incremental_rescan_args(24, project.as_deref());
            match std::process::Command::new("aicx")
                .args(&args)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
            {
                Ok(_) => {
                    std::thread::spawn(|| {
                        std::thread::sleep(std::time::Duration::from_secs(30));
                        RESCAN_RUNNING.store(false, Ordering::SeqCst);
                    });
                }
                Err(e) => {
                    tracing::warn!("Failed to spawn aicx background refresh: {e}");
                    RESCAN_RUNNING.store(false, Ordering::SeqCst);
                }
            }
        }

        // Try fast search with rmcp_memex first (instant), fallback to brute-force if it fails
        let (results, scanned) = match crate::memex::fast_memex_search(
            &query,
            fetch_limit,
            project.as_deref(),
            frame_kind,
        )
        .await
        {
            Ok((res, scan)) if !res.is_empty() => (res, scan),
            Err(err) if crate::memex::is_compatibility_error(&err) => {
                return Err(McpError::internal_error(
                    format!("Search index incompatible: {err}"),
                    None,
                ));
            }
            _ => {
                // Fallback to reading all markdown files sequentially (slow)
                let store_root = store::store_base_dir()
                    .map_err(|e| McpError::internal_error(format!("Store error: {e}"), None))?;
                rank::fuzzy_search_store(
                    &store_root,
                    &query,
                    fetch_limit,
                    project.as_deref(),
                    frame_kind,
                )
                .map_err(|e| McpError::internal_error(format!("Read store: {e}"), None))?
            }
        };

        let mut results = results;

        if let Some(min_score) = score {
            results.retain(|result| result.score >= min_score);
        }
        if let Some(ref agent_filter) = params.agent {
            results.retain(|r| r.agent == *agent_filter);
        }

        let date_effective = date.or(params.since.clone());
        let (lo, hi) = if let Some(ref date_filter) = date_effective {
            parse_date_filter_mcp(date_filter)
        } else {
            (None, params.until.clone())
        };

        let mut results: Vec<_> = if lo.is_some() || hi.is_some() {
            results
                .into_iter()
                .filter(|result| {
                    lo.as_ref()
                        .is_none_or(|lo| result.date.as_str() >= lo.as_str())
                        && hi
                            .as_ref()
                            .is_none_or(|hi| result.date.as_str() <= hi.as_str())
                })
                .collect()
        } else if hours > 0 {
            let cutoff = chrono::Utc::now() - chrono::Duration::hours(hours as i64);
            let cutoff_date = cutoff.format("%Y-%m-%d").to_string();
            results
                .into_iter()
                .filter(|result| result.date >= cutoff_date)
                .collect()
        } else {
            results
        };

        if let Some(sort_order) = params.sort.as_deref() {
            results.sort_by(|a, b| {
                let t_a = a.timestamp.as_deref().unwrap_or(a.date.as_str());
                let t_b = b.timestamp.as_deref().unwrap_or(b.date.as_str());
                match sort_order {
                    "newest" => t_b.cmp(t_a),
                    "oldest" => t_a.cmp(t_b),
                    "score" => b.score.cmp(&a.score).then(t_b.cmp(t_a)),
                    _ => t_b.cmp(t_a),
                }
            });
        } else {
            results.sort_by(|a, b| b.score.cmp(&a.score));
        }

        let results: Vec<_> = results.into_iter().take(limit).collect();

        let json = rank::render_search_json(&results, scanned)
            .map_err(|e| McpError::internal_error(format!("Serialize search JSON: {e}"), None))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        name = "aicx_rank",
        description = "Rank stored AI session chunks by content quality. Shows signal density, noise ratio, and quality labels (HIGH/MEDIUM/LOW/NOISE) per chunk. Use --strict to filter noise."
    )]
    async fn rank_artifacts(
        &self,
        Parameters(params): Parameters<RankParams>,
    ) -> Result<CallToolResult, McpError> {
        let project = params.project;
        let hours = params.hours;
        let strict = params.strict;
        let top = params.top;

        let cutoff = std::time::SystemTime::now()
            - std::time::Duration::from_secs(hours.saturating_mul(3600).min(365 * 24 * 3600));
        let mut scored = Vec::new();

        let (lo, hi) = if let Some(ref d) = params.since {
            parse_date_filter_mcp(d)
        } else {
            (None, params.until.clone())
        };

        let files = store::context_files_since(cutoff, Some(&project))
            .map_err(|e| McpError::internal_error(format!("Store error: {e}"), None))?;

        for file in files {
            if file.path.extension().is_none_or(|ext| ext != "md") {
                continue;
            }
            if let Some(ref agent_filter) = params.agent
                && file.agent != *agent_filter
            {
                continue;
            }
            if lo
                .as_ref()
                .is_some_and(|lo| file.date_iso.as_str() < lo.as_str())
                || hi
                    .as_ref()
                    .is_some_and(|hi| file.date_iso.as_str() > hi.as_str())
            {
                continue;
            }

            let cs = rank::score_chunk_file(&file.path);
            if strict && cs.score < 5 {
                continue;
            }

            let sidecar_path = file.path.with_extension("meta.json");
            let timestamp = if sidecar_path.exists() {
                crate::sanitize::read_to_string_validated(&sidecar_path)
                    .ok()
                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
                    .and_then(|v| {
                        v.get("started_at")
                            .and_then(|s| s.as_str())
                            .map(String::from)
                            .or_else(|| {
                                v.get("timestamp")
                                    .and_then(|s| s.as_str())
                                    .map(String::from)
                            })
                    })
            } else {
                None
            };
            let final_timestamp = timestamp.or_else(|| {
                file.path
                    .metadata()
                    .ok()
                    .and_then(|m| m.modified().ok())
                    .map(chrono::DateTime::<chrono::Utc>::from)
                    .map(|d| d.to_rfc3339())
            });

            scored.push(RankItem {
                file: file
                    .path
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
                project: file.project,
                date: file.date_iso,
                timestamp: final_timestamp,
                kind: file.kind.dir_name().to_string(),
                agent: file.agent,
                score: cs.score,
                label: cs.label.to_string(),
                signal: cs.signal_lines,
                noise: cs.noise_lines,
                total: cs.total_lines,
                density: format!("{:.0}%", cs.density * 100.0),
            });
        }

        if let Some(sort_order) = params.sort.as_deref() {
            scored.sort_by(|a, b| {
                let t_a = a.timestamp.as_deref().unwrap_or(a.date.as_str());
                let t_b = b.timestamp.as_deref().unwrap_or(b.date.as_str());
                match sort_order {
                    "newest" => t_b.cmp(t_a),
                    "oldest" => t_a.cmp(t_b),
                    "score" => b.score.cmp(&a.score).then(t_b.cmp(t_a)),
                    _ => t_b.cmp(t_a),
                }
            });
        } else {
            scored.sort_by(|a, b| b.score.cmp(&a.score).then_with(|| b.date.cmp(&a.date)));
        }

        if let Some(n) = top {
            scored.truncate(n);
        }

        let json = serde_json::to_string(&RankResponse {
            project,
            hours,
            strict,
            results: scored.len(),
            items: scored,
        })
        .map_err(|e| McpError::internal_error(format!("Serialize rank JSON: {e}"), None))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        name = "aicx_steer",
        description = "Retrieve stored chunks by steering metadata (frontmatter fields). Filters by run_id, prompt_id, agent, kind, project, and/or date range using sidecar metadata — no filesystem grep needed. Returns chunk paths with their sidecar metadata for selective re-entry."
    )]
    async fn steer(
        &self,
        Parameters(params): Parameters<SteerParams>,
    ) -> Result<CallToolResult, McpError> {
        let limit = params.limit.min(100);

        let date_effective = params.date.or(params.since.clone());
        let (date_lo, date_hi) = if let Some(ref d) = date_effective {
            parse_date_filter_mcp(d)
        } else {
            (None, params.until.clone())
        };

        let mut metadatas = crate::steer_index::search_steer_index(
            params.run_id.as_deref(),
            params.prompt_id.as_deref(),
            params.agent.as_deref(),
            params.kind.as_deref(),
            params.frame_kind,
            params.project.as_deref(),
            date_lo.as_deref(),
            date_hi.as_deref(),
            limit,
        )
        .await
        .map_err(|e| McpError::internal_error(format!("Index error: {e}"), None))?;

        if let Some(min_score) = params.score {
            metadatas.retain(|m| {
                let score = m.get("score").and_then(|v| v.as_u64()).unwrap_or(0) as u8;
                score >= min_score
            });
        }

        if let Some(sort_order) = params.sort.as_deref() {
            metadatas.sort_by(|a, b| {
                let t_a = a
                    .get("timestamp")
                    .and_then(|v| v.as_str())
                    .or_else(|| a.get("date").and_then(|v| v.as_str()))
                    .unwrap_or("");
                let t_b = b
                    .get("timestamp")
                    .and_then(|v| v.as_str())
                    .or_else(|| b.get("date").and_then(|v| v.as_str()))
                    .unwrap_or("");
                match sort_order {
                    "newest" => t_b.cmp(t_a),
                    "oldest" => t_a.cmp(t_b),
                    "score" => {
                        let s_a = a.get("score").and_then(|v| v.as_u64()).unwrap_or(0);
                        let s_b = b.get("score").and_then(|v| v.as_u64()).unwrap_or(0);
                        s_b.cmp(&s_a).then(t_b.cmp(t_a))
                    }
                    _ => t_b.cmp(t_a),
                }
            });
        }

        let json = serde_json::to_string(&SteerResponse {
            results: metadatas.len(),
            items: metadatas,
        })
        .map_err(|e| McpError::internal_error(format!("Serialize steer JSON: {e}"), None))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }
}

// ============================================================================
// ServerHandler impl
// ============================================================================

#[rmcp::tool_handler]
impl rmcp::handler::server::ServerHandler for AicxMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new("aicx-mcp", env!("CARGO_PKG_VERSION")))
    }
}

// ============================================================================
// Server runners
// ============================================================================

/// Run MCP server over stdio transport.
pub async fn run_stdio() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_writer(std::io::stderr)
        .try_init()
        .ok();

    let server = AicxMcpServer::new();
    let service = rmcp::ServiceExt::serve(server, rmcp::transport::io::stdio())
        .await
        .map_err(|e| anyhow::anyhow!("MCP stdio serve failed: {e}"))?;

    eprintln!("aicx MCP server running (stdio)");
    service
        .waiting()
        .await
        .map_err(|e| anyhow::anyhow!("MCP server error: {e}"))?;
    Ok(())
}

/// Run MCP server over streamable HTTP transport on given port.
pub async fn run_http(port: u16) -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_writer(std::io::stderr)
        .try_init()
        .ok();

    let addr = std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), port);

    let config = rmcp::transport::streamable_http_server::StreamableHttpServerConfig::default();
    let service = rmcp::transport::streamable_http_server::StreamableHttpService::new(
        || Ok(AicxMcpServer::new()),
        std::sync::Arc::new(
            rmcp::transport::streamable_http_server::session::local::LocalSessionManager::default(),
        ),
        config,
    );

    let app = axum::Router::new().route(
        "/mcp",
        axum::routing::any(move |req: axum::http::Request<axum::body::Body>| {
            let svc = service.clone();
            async move { svc.handle(req).await }
        }),
    );

    let listener = tokio::net::TcpListener::bind(addr)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to bind MCP server on {addr}: {e}"))?;

    eprintln!("aicx MCP server running (streamable HTTP)");
    eprintln!("  Endpoint: http://{addr}/mcp");
    eprintln!("  Transport: Streamable HTTP (POST + GET /mcp)");

    axum::serve(listener, app)
        .await
        .map_err(|e| anyhow::anyhow!("MCP HTTP server error: {e}"))
}

/// Legacy compatibility wrapper for callers that still use the old `run_sse` name.
pub async fn run_sse(port: u16) -> anyhow::Result<()> {
    run_http(port).await
}

/// Run the selected MCP transport.
pub async fn run_transport(transport: McpTransport, port: u16) -> anyhow::Result<()> {
    match transport {
        McpTransport::Stdio => run_stdio().await,
        McpTransport::Http => run_http(port).await,
    }
}

/// Parse a date filter string into (optional_low, optional_high) bounds.
///
/// Accepted formats:
/// - `2026-03-28` → exact day
/// - `2026-03-20..2026-03-28` → inclusive range
/// - `2026-03-20..` → open-ended (from date onward)
/// - `..2026-03-28` → open-ended (up to date)
fn parse_date_filter_mcp(date: &str) -> (Option<String>, Option<String>) {
    if let Some((lo, hi)) = date.split_once("..") {
        let lo = if lo.is_empty() {
            None
        } else {
            Some(lo.to_string())
        };
        let hi = if hi.is_empty() {
            None
        } else {
            Some(hi.to_string())
        };
        (lo, hi)
    } else {
        (Some(date.to_string()), Some(date.to_string()))
    }
}

fn validate_score_filter(score: Option<u8>) -> Result<Option<u8>, McpError> {
    match score {
        Some(score) if score > MAX_SCORE_FILTER => Err(McpError::invalid_params(
            format!("score must be between 0 and {MAX_SCORE_FILTER}"),
            None,
        )),
        _ => Ok(score),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        MAX_SCORE_FILTER, McpTransport, RankItem, RankResponse, SearchParams, SteerResponse,
        incremental_rescan_args, parse_date_filter_mcp, validate_score_filter,
    };
    use clap::ValueEnum as _;

    #[test]
    fn incremental_rescan_args_use_all_incremental_and_quiet_stdout() {
        assert_eq!(
            incremental_rescan_args(24, None),
            vec![
                "all".to_string(),
                "-H".to_string(),
                "24".to_string(),
                "--incremental".to_string(),
                "--emit".to_string(),
                "none".to_string(),
            ]
        );
    }

    #[test]
    fn parse_date_filter_mcp_exact_day() {
        let (lo, hi) = parse_date_filter_mcp("2026-03-28");
        assert_eq!(lo.as_deref(), Some("2026-03-28"));
        assert_eq!(hi.as_deref(), Some("2026-03-28"));
    }

    #[test]
    fn parse_date_filter_mcp_range() {
        let (lo, hi) = parse_date_filter_mcp("2026-03-20..2026-03-28");
        assert_eq!(lo.as_deref(), Some("2026-03-20"));
        assert_eq!(hi.as_deref(), Some("2026-03-28"));
    }

    #[test]
    fn parse_date_filter_mcp_open_ended() {
        let (lo, hi) = parse_date_filter_mcp("2026-03-20..");
        assert_eq!(lo.as_deref(), Some("2026-03-20"));
        assert!(hi.is_none());

        let (lo, hi) = parse_date_filter_mcp("..2026-03-28");
        assert!(lo.is_none());
        assert_eq!(hi.as_deref(), Some("2026-03-28"));
    }

    #[test]
    fn incremental_rescan_args_include_project_filter() {
        assert_eq!(
            incremental_rescan_args(72, Some("ai-contexters")),
            vec![
                "all".to_string(),
                "-H".to_string(),
                "72".to_string(),
                "--incremental".to_string(),
                "--emit".to_string(),
                "none".to_string(),
                "-p".to_string(),
                "ai-contexters".to_string(),
            ]
        );
    }

    #[test]
    fn rank_response_serializes_as_compact_json() {
        let json = serde_json::to_string(&RankResponse {
            project: "VetCoders/ai-contexters".to_string(),
            hours: 72,
            strict: true,
            results: 1,
            items: vec![RankItem {
                file: "chunk.md".to_string(),
                project: "VetCoders/ai-contexters".to_string(),
                date: "2026-03-31".to_string(),
                timestamp: Some("2026-03-31T10:00:00Z".to_string()),
                kind: "reports".to_string(),
                agent: "codex".to_string(),
                score: 8,
                label: "HIGH".to_string(),
                signal: 14,
                noise: 2,
                total: 20,
                density: "70%".to_string(),
            }],
        })
        .expect("rank response should serialize");

        assert!(!json.contains('\n'));

        let payload: serde_json::Value =
            serde_json::from_str(&json).expect("rank JSON should parse");
        assert_eq!(payload["results"], 1);
        assert_eq!(payload["items"][0]["score"], 8);
        assert_eq!(payload["items"][0]["label"], "HIGH");
    }

    #[test]
    fn steer_response_serializes_as_compact_json() {
        let json = serde_json::to_string(&SteerResponse {
            results: 1,
            items: vec![serde_json::json!({
                "path": "/tmp/chunk.md",
                "project": "VetCoders/ai-contexters",
                "agent": "codex",
                "kind": "reports",
            })],
        })
        .expect("steer response should serialize");

        assert!(!json.contains('\n'));

        let payload: serde_json::Value =
            serde_json::from_str(&json).expect("steer JSON should parse");
        assert_eq!(payload["results"], 1);
        assert_eq!(payload["items"][0]["path"], "/tmp/chunk.md");
        assert_eq!(payload["items"][0]["agent"], "codex");
    }

    #[test]
    fn search_params_roundtrip_include_new_optional_filters() {
        let params: SearchParams =
            serde_json::from_str(r#"{"query":"dashboard"}"#).expect("search params should parse");
        assert_eq!(params.limit, 10);
        assert!(params.project.is_none());
        assert!(params.score.is_none());
        assert!(params.hours.is_none());
        assert!(params.date.is_none());
    }

    #[test]
    fn score_filter_rejects_values_above_max() {
        let err = validate_score_filter(Some(MAX_SCORE_FILTER + 1))
            .expect_err("score above 100 should be rejected");
        assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS);
    }

    #[test]
    fn mcp_transport_prefers_http_but_accepts_legacy_sse_alias() {
        let possible = McpTransport::value_variants()
            .iter()
            .map(|variant| {
                variant
                    .to_possible_value()
                    .expect("possible value")
                    .get_name()
                    .to_string()
            })
            .collect::<Vec<_>>();

        assert_eq!(possible, vec!["stdio".to_string(), "http".to_string()]);
        assert_eq!(McpTransport::from_str("http", true), Ok(McpTransport::Http));
        assert_eq!(McpTransport::from_str("sse", true), Ok(McpTransport::Http));
    }
}