neosian 2.17.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The memory-search CLI shares its validation and result with MCP.

use clap::Args;
use std::io::Write;

use super::{Order, Request, mounted};
use crate::memory::dispatch::Memory;
use crate::store::error::Error;

#[derive(Args)]
#[group(id = "MemorySearchOptions")]
pub struct Search {
    /// Whitespace-separated terms; relevance needs one to match, path and newest every one.
    query: String,
    /// Mounted path prefix; / searches all mounted memory.
    #[arg(long, default_value = "/")]
    path: String,
    /// Select fields; repeat for multiple fields (default: path and content).
    #[arg(long = "field", value_parser = ["path", "content", "metadata"])]
    fields: Vec<String>,
    /// Top-level extra key whose string values are searched; requires --field metadata.
    #[arg(long = "metadata-key")]
    metadata_keys: Vec<String>,
    /// Hits per page, between 1 and 100.
    #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u32).range(1..=100))]
    limit: u32,
    /// Opaque continuation returned by the previous identical query (path order only).
    #[arg(long)]
    cursor: Option<String>,
    /// Result order: relevance (default), newest, or path (pageable).
    #[arg(long, value_enum)]
    order: Option<Order>,
    /// Only documents updated at or after this UTC instant (RFC 3339 ending in Z).
    #[arg(long)]
    updated_since: Option<String>,
    /// Only documents updated before this UTC instant (RFC 3339 ending in Z).
    #[arg(long)]
    updated_before: Option<String>,
    /// Matched passages per hit from long documents, 0 to 3 (default 3).
    #[arg(long, value_parser = clap::value_parser!(u8).range(0..=3))]
    passages: Option<u8>,
    /// Review policy; a selected profile may require a stricter policy.
    #[arg(long, value_enum, default_value = "all")]
    knowledge_policy: crate::knowledge::governance::Policy,
}

impl Search {
    fn request(&self) -> Request {
        Request {
            query: self.query.clone(),
            prefix: String::new(),
            fields: if self.fields.is_empty() {
                super::fields()
            } else {
                self.fields.clone()
            },
            metadata_keys: self.metadata_keys.clone(),
            limit: self.limit as usize,
            cursor: self.cursor.clone(),
            knowledge_policy: self.knowledge_policy,
            order: self.order,
            updated_since: self.updated_since.clone(),
            updated_before: self.updated_before.clone(),
            passages: self.passages,
        }
    }
    pub fn validate(&self, mounts: &[crate::memory::mounts::Mount]) -> Result<(), String> {
        self.request().validate()?;
        mounted::selection(mounts, &self.path)
            .map_err(|e| crate::conversation::Error::from(e).text())?;
        Ok(())
    }
    pub fn run(&self, memory: &Memory, json: bool, out: &mut impl Write) -> Result<u8, Error> {
        let page = mounted::run(memory, &self.path, &self.request())?;
        if json {
            writeln!(
                out,
                "{}",
                serde_json::to_string(&page).expect("search page serializes")
            )?;
        } else {
            writeln!(out, "order: {}", page.order.unwrap_or(Order::Path).name())?;
            if let Some(reason) = &page.fallback {
                writeln!(out, "fallback: {reason}")?;
            }
            for hit in page.hits {
                let score = hit
                    .score
                    .map(|s| format!(", score={s}"))
                    .unwrap_or_default();
                writeln!(
                    out,
                    "{} (v{}{score}, scope={}, actor={}):\n{}",
                    hit.reference.as_deref().unwrap_or(&hit.path),
                    hit.version,
                    hit.scope,
                    hit.actor.as_deref().unwrap_or("-"),
                    hit.excerpt.text
                )?;
                for passage in hit.passages.unwrap_or_default() {
                    let heading = passage
                        .heading
                        .map(|h| format!(" ({h})"))
                        .unwrap_or_default();
                    writeln!(
                        out,
                        "  passage {}{heading}: {}",
                        passage.offset, passage.text
                    )?;
                }
            }
            if let Some(cursor) = page.next_cursor {
                writeln!(out, "next_cursor: {cursor}")?;
            }
        }
        Ok(0)
    }
}